Search code examples
rslicecopy-on-write

Is slicing copy-on-modify in R?


It is mentioned here that R use copy-on-modify when assigning a variable to a new one, including passing parameter to a function.

However, does slicing (vector, list, data frame) create a new object, of the same type, that contains oopies of the subset of the original object, or is the elements store in the new object a copy of the original one or just a copy-on-modify reference?


Solution

  • This is a complex topic. You should start with reading about the NAMED mechanism.

    If you run the following, you see that there is no copy of the list elements (because lists are basically pointers to their elements):

    > a <- list(1, 2, 3, 4, 5)
    > 
    > b <- a[1:2]
    > .Internal(inspect(b)) 
    @0x000000001327e5b8 19 VECSXP g0c2 [NAM(3)] (len=2, tl=0)
      @0x00000000136f6b60 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 1
      @0x00000000136f6b28 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 2
    > 
    > 
    > c <- a[1:2]
    > .Internal(inspect(c)) 
    @0x000000001327e678 19 VECSXP g0c2 [NAM(3)] (len=2, tl=0)
      @0x00000000136f6b60 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 1
      @0x00000000136f6b28 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 2
    > 
    > b[1] <- 6
    > .Internal(inspect(b)) 
    @0x000000001327e6f8 19 VECSXP g0c2 [NAM(1)] (len=2, tl=0)
      @0x0000000013745b58 14 REALSXP g0c1 [] (len=1, tl=0) 6
      @0x00000000136f6b28 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 2
    > 
    > .Internal(inspect(c))
    @0x000000001327e678 19 VECSXP g0c2 [NAM(3)] (len=2, tl=0)
      @0x00000000136f6b60 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 1
      @0x00000000136f6b28 14 REALSXP g0c1 [NAM(3)] (len=1, tl=0) 2
    

    This is different if you subset vectors.

    You might also be interested in the new reference counting mechanism.