I was trying to do something similar to what is described here:
Apply a function to every specified column in a data.table and update by reference
But I created a new copy (called dt.2) of the original data table (called dt) before applying the function. So:
library(data.table)
dt <- data.table(a = 1:3, b = 1:3, d = 1:3)
dt.2 = dt
cols <- c("a", "b")
dt.2[ , (cols) := lapply(.SD, "*", -1), .SDcols = cols]
What I am puzzled is that this applies the function to both the original data table and the copy! So you get
> dt.2
a b d
1: -1 -1 1
2: -2 -2 2
3: -3 -3 3
> dt
a b d
1: -1 -1 1
2: -2 -2 2
3: -3 -3 3
>
Why does this happen? why does the function modify the original variable?
thanks