0

I am creating a copy of an object, and then when I manipulate the copy, also the original is changed. Is anyone familiar with this?

Reproducible example -

a <- data.table(av = c(1, 2, 3, 4, 5), bv = rnorm(5))

b <- a

b[, av:=factor(av)]

str(a) # av is a factor...

R version 4.2.0

data.table 1.14.2

s_baldur
  • 29,441
  • 4
  • 36
  • 69
YuvalOS
  • 1
  • 2
  • I can reproduce it, but don't know the answer. In that way it won't get manipulated. library(data.table) a <- data.table(av = c(1, 2, 3, 4, 5), bv = rnorm(5)) b <- a b<- b[, as.factor(av)] str(a) str(b) – pbraeutigm Jun 13 '22 at 09:04
  • 3
    You're not creating a copy of the data but just another name for the same data. So, `b` is just a shallow copy and not a deep one. data.table package modifies the data by reference and that's why what you call _copy_ also gets modified. If you want a (deep) copy of the data, you should use `b <- copy(a)` after loading data.table package. – B. Christian Kamgang Jun 13 '22 at 09:25

0 Answers0