Creating new variable and save in new object in data table in R

Viewed 309

This may be very elementary question. I wanted to create a new variable in existing data.table object, and wanted to save the new object with different name. However, I am facing a problem:

library(data.table)
DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9)

a <- colnames(DT)[-1] #variables to be modified
a.va <- paste(a, "x", sep = "_") #new variables name

DT2 <- DT[, (a.va) := lapply(.SD, FUN = function(x) (sum(x, na.rm = T)-x) / (.N - 1)), .SDcols = a, by = x]

However, it changes the both existing object DT as well. I wanted to keep the original object DT as intact. In my original data set, there are more than 100 variables, so I can not create one by one separate variable.

1 Answers

The := will change the current object while adding a new column as it does by reference. If we want a new object, use copy to create a new object from 'DT', then do the assignment := on the copied object

DT2 <- copy(DT)
DT2[, (a.va) := lapply(.SD, FUN = function(x) (sum(x, na.rm = T)-x) / (.N - 1)), .SDcols = a, by = x]

-checking

> names(DT2)
[1] "x"   "y"   "v"   "y_x" "v_x"
> names(DT)
[1] "x" "y" "v"
Related