[datatable-help] extracting columns dynamically

Ben Tupper btupper at bigelow.org
Thu Feb 12 22:27:56 CET 2015


Hello,

I would like to extract a column of a data.table, but I get unexpected (to me) results when I specify a column dynamically. 

DT <- data.table(ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18)
thisone = "a"

str(DT[,a])
#  int [1:6] 1 2 3 4 5 6

str(DT[,"a", with = FALSE])
# Classes ‘data.table’ and 'data.frame':	6 obs. of  1 variable:
# $ a: int  1 2 3 4 5 6
# - attr(*, ".internal.selfref")=<externalptr>

str(DT[, thisone, with = FALSE])
# Classes ‘data.table’ and 'data.frame':	6 obs. of  1 variable:
# $ a: int  1 2 3 4 5 6
# - attr(*, ".internal.selfref")=<externalptr> 

I can't noodle out from the help why the latter two don't produce a vector as the first one does. I'm looking at this online resource http://www.rdocumentation.org/packages/data.table/functions/data.table and it doesn't seem like the description of with points to having two different results.

"with		By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. When with=FALSE, j is a vector of names or positions to select, similar to a data.frame. with=FALSE is often useful in data.table to select columns dynamically."

How should I extract a single column dynamically to retrieve a vector?   

Cheers and thanks,
Ben

> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.9.5 devtools_1.6.1  

loaded via a namespace (and not attached):
[1] chron_2.3-45   evaluate_0.5.5 formatR_1.0    httr_0.5       knitr_1.7      RCurl_1.95-4.1 stringr_0.6.2 
[8] tools_3.1.0

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org










More information about the datatable-help mailing list