Select / assign to data.table when variable names are stored in a character vector

后端 未结 5 1432
無奈伤痛
無奈伤痛 2020-11-22 03:54

How do you refer to variables in a data.table if the variable names are stored in a character vector? For instance, this works for a data.frame:

5条回答
  •  爱一瞬间的悲伤
    2020-11-22 04:18

    Retrieve multiple columns from data.table via variable or function:

    library(data.table)
    
    x <- data.table(this=1:2,that=1:2,whatever=1:2)
    
    # === explicit call
    x[, .(that, whatever)]
    x[, c('that', 'whatever')]
    
    # === indirect via  variable
    # ... direct assignment
    mycols <- c('that','whatever')
    # ... same as result of a function call
    mycols <- grep('a', colnames(x), value=TRUE)
    
    x[, ..mycols]
    x[, .SD, .SDcols=mycols]
    
    # === direct 1-liner usage
    x[, .SD, .SDcols=c('that','whatever')]
    x[, .SD, .SDcols=grep('a', colnames(x), value=TRUE)]
    

    which all yield

       that whatever
    1:    1        1
    2:    2        2
    

    I find the .SDcols way the most elegant.

提交回复
热议问题