简体   繁体   中英

Referring to a column through a character variable in data.table R

I am using data.table and I want to filter a data.table within a function where I am passing the name of the column as a character vector.

For a simple reproducible example let's take the mtcars dataset of base R.

I can write using data.table syntax:

mtcars[am == 1, .N ]

But what if the name of the variable of interest -- ie am -- is stored as a character vector, ie "am"?

Your advice will be appreciated.

One option is to use get ( ?get search object by name):

mtcars[get('am') == 1, .N]
# [1] 13

Another option is to specify it in the .SDcols

mtcars[, sum(.SD==1) ,.SDcols = 'am']
#[1] 13

We can also include multiple variables

mtcars[, sum(Reduce(`&`, lapply(.SD, `==`, 1))), .SDcols = c('am', 'carb')]
#[1] 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM