R Data table copy and modification alters original one [duplicate] R Data table copy and modification alters original one [duplicate] r r

R Data table copy and modification alters original one [duplicate]


When you assign a new variable to an already existing variable, R doesn't create a copy, but just points to the new variable, which is very nice as you don't want to make copies unless you absolutely need to - copy on modify.

After this, since you use the:= operator, which modifies in-place (by reference), and since at the moment, both objects are pointing to the same location, it gets reflected on both the objects.

The fix is to explicitly copy the data.table using copy() function and then assign by reference as follows:

dtt = copy(dt)     ## dt and dtt are not pointing to same locations anymoredtt[, pc := pc*2]  ## assignment by reference doesn't affect dt

HTH