R Advanced

What is copy-on-modify Semantics in R

The copy-on-modify semantics is a memory management technique that modifies one or more objects, copies those objects to a new location in memory, and makes some modifications there, leaving the original unchanged.

There are two types of copying in R:

  1. Lazy copying
  2. Copy-on-modify

Lazy copying

When you assign an existing object to a new variable, the underlying data is not directly copied. Instead, both variables point to the same memory.

Here is the figure that shows that:

In this figure, I explained how you could define a vector “x” and assign that vector to a new variable “y”, and both points to the exact memory location instead of different.

Here is a code example:

x <- c(1, 2, 3)
y <- x

print(y)

Output

[1] 1  2  3

Here, no actual copy of the data in ‘y’ is made. It pointed to the memory location of ‘x’, which has 1 2 3 values.

Copy-on-Modify

The copy-on-modify means it will create an actual copy when the copied variable is modified. In our previous example, when you modify the variable “y”, it will create a new copy with a different memory location.

In the above figure, we first created a lazy copy of data “x”, which is “y” and then created an actual copy by modifying “y”.

Here is a code that explains this figure:

x <- c(1, 2, 3)
y <- x

y[2] <- 4

print(y)

Output

[1] 1  4  3

Before modification, “x” and “y” refer to the same memory location, but after modification, both “x” and “y” refer to different memory locations because now “y” is an independent copied variable with its memory location.

Now, “x” refers to the original data, and “y” refers to the modified copied data.

Recent Posts

Unlocking Statistical Consistency with set.seed in R

Picture this: You are playing Snakes and Ladder and need the dice to roll the…

2 months ago

How to Find Standard deviation in R [Using Real-life DataSet]

The standard deviation is a measure that tells you how spread out data are in…

9 months ago

How to Calculate Mean in R

Mean means the arithmetic average of a number in mathematics. An average is the sum…

9 months ago

How to Append an Element to a List at Any Position in R

List in R is a data structure that can hold multiple types of elements. You…

9 months ago

R ln() Function (SciViews Package)

The ln() function from the SciViews package calculates the natural log of the input vector.…

12 months ago

How to Convert List to Numeric in R

To convert a list to a numeric value in R, you can combine the unlist()…

12 months ago