8
votes

Suppose I have an R data.table:

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

and I have a character vector of column names that I would like to extract, or more generally operate on:

cols = c("x","y")

For example, how can I use cols to generate the equivalent of

 DT[,lapply(.SD[,list(x,y)], min) ]

Is there a way to specify the list(x,y) using the cols vector?

1

1 Answers

7
votes

You can use the data.table syntax .. which "looks up one level" (as in the Unix terminal) for the variable:

> all.equal(DT[,list(x,y)], DT[, ..cols])
[1] TRUE
> all.equal(DT[,.SD[,list(x,y)][min(v)]], DT[,.SD[ ,min(v)], .SDcols = cols])
[1] TRUE

More details under FAQ 1.6 I believe: http://datatable.r-forge.r-project.org/datatable-faq.pdf