How to select columns in data.table using a character vector of certain column names?

Rdata.table

R Problem Overview


I am trying to select those columns in a data.table whose name appears in my character vector. The operation works in a pure data.frame, but doesn't work in a data.table. Here's a reproducible example.

> names(mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
> myVector <- c('disp', 'hp', 'wt')
> head(mtcars[, myVector])
                  disp  hp    wt
Mazda RX4          160 110 2.620
Mazda RX4 Wag      160 110 2.875
Datsun 710         108  93 2.320
Hornet 4 Drive     258 110 3.215
Hornet Sportabout  360 175 3.440
Valiant            225 105 3.460

I just made a vector which includes disp, hp, and wt and I selected the corresponding columns in my data.frame using that vector. Let's now make a data.table object from my data.frame and try to do the same operation.

> library(data.table)
> mtcarsDT <- data.table(mtcars)
> mtcarsDT[, myVector]
[1] "disp" "hp"   "wt"  

R Solutions


Solution 1 - R

We can use .. notation to find myVector as a vector of column positions, like it would work in data.frame

mtcarsDT[, ..myVector]

According to ?data.table

> In case of overlapping variables names inside dataset and in parent scope you can use double dot prefix ..cols to explicitly refer to 'cols variable parent scope and not from your dataset.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionconeyhelixlakeView Question on Stackoverflow
Solution 1 - RakrunView Answer on Stackoverflow