data.table Creating a data.table Copy another data.table with copy()


Example

# example data
DT1 = data.table(x = letters[1:2], y = 1:2, z = (1:2) > 3)

Due to the way data.tables are manipulated, DT2 <- DT1 will not make a copy. That is, later modifications to the columns or other attributes of DT2 will affect DT1 as well. When you want a real copy, use

DT2 = copy(DT1)

To see the difference, here's what happens without a copy:

DT2 <- DT1
DT2[, w := 1:2]

DT1
#    x y     z w
# 1: a 1 FALSE 1
# 2: b 2 FALSE 2
DT2
#    x y     z w
# 1: a 1 FALSE 1
# 2: b 2 FALSE 2

And with a copy:

DT2 <- copy(DT1)
DT2[, w := 1:2]

DT1
#    x y     z
# 1: a 1 FALSE
# 2: b 2 FALSE
DT2
#    x y     z w
# 1: a 1 FALSE 1
# 2: b 2 FALSE 2

So the changes do not propagate in the latter case.