Reputation: 2367
This is related to my earlier question on convenience of data.table
for loops and functions: How to use data.table within functions and loops? and related post: Data.table meta-programming.
This little code shows how conveniently this is done with data.table
it is (e.g. compare to dplyr
).
At first, I got cannot change value of locked binding for '.SD'
error when I use get(strY)
or .SD
/ .SDcols=colY
below. But when I restarted the R Session, it all worked.
dt <- data.table(ggplot2::diamonds)
nY <- 1; nX <- c(5:7)
strY <- names(dt)[nY]; strX <- names(dt)[nX];
dt[,strY, with=F] # OK
dt[,nY, with=F] # OK
dt[,get(strY)] # OK NOW:
#NO MORE: Error in assign(ii, SDenv$.SDall[[ii]], SDenv) :
# cannot change value of locked binding for '.SD'
dt[, .SD, .SDcols=strX] # OK NOW:
#NO MORE Error in assign(ii, SDenv$.SDall[[ii]], SDenv) :
# cannot change value of locked binding for '.SD'
Upvotes: 1
Views: 1974
Reputation: 2367
This problem was resolved somehow by restarting the R session. - All lines work. This code has become the key work-stone for all my loop/function needs. Thanks to reviewers!
Upvotes: 5