1

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'
Community
  • 1
  • 1
IVIM
  • 2,167
  • 1
  • 15
  • 41
  • I don't see the error you are "get"-ting. My console fills up with 53K values. Uggh. – IRTFM Mar 03 '17 at 22:29
  • Add `library()` statements. There is no diamonds data set available in my r session. – Frank Mar 03 '17 at 22:33
  • 1
    Anyway, `dt[, ..strY]` works fine for me, as does all of the code that is giving you errors. – Frank Mar 03 '17 at 22:35
  • You can find the link to delete your question below it. Otherwise, I guess you could post an answer further down, but I don't think this'll be of much benefit to future visitors. – Frank Mar 06 '17 at 15:44
  • 2
    I think this question is useful. Knowing that this error is solved by restarting the session clearly helped me. Maybe rephrase in a simpler way. – Picarus May 27 '17 at 09:10

1 Answers1

5

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!

IVIM
  • 2,167
  • 1
  • 15
  • 41