0

just found an interesting thing that the operation on one variable, it shall affect another twin variable, when working with data.table

library(data.table)
data("mtcars")
elder.brother <- data.table(mtcars)
paste("elder brother = ",length(elder.brother),sep="")

younger.brother <- elder.brother
paste("younger brother = ",length(younger.brother),sep="")

younger.brother[,c(1:10):= NULL]
paste("the younger brother = ",length(younger.brother), 
      " and the older brother = ",length(elder.brother), " too!",sep="")

when y is altered, the x changes too, just like this

> data("mtcars")
> elder.brother <- data.table(mtcars)
> paste("elder brother = ",length(elder.brother),sep="")
[1] "elder brother = 11"

> younger.brother <- elder.brother
> paste("younger brother = ",length(younger.brother),sep="")
[1] "younger brother = 11"

> younger.brother[,c(1:10):= NULL]
> paste("the younger brother = ",length(younger.brother), 
+       " and the older brother = ",length(elder.brother), " too!",sep="")

[1] "the younger brother = 1 and the older brother = 1 too!"

Is it normal? But it is strange for Rookie like I am.

Grec001
  • 1,111
  • 6
  • 20

0 Answers0