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:

Lazy copying in R

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



[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.


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



[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.

Leave a Comment