How to select columns programmatically in a data.table?

前端 未结 2 807
醉酒成梦
醉酒成梦 2020-12-03 07:46

I have the following data.table (DT):

DT <- data.table(V1 = 1:3, V2 = 4:6, V3 = 7:9)

I would like to select a subset of the variables pr

相关标签:
2条回答
  • 2020-12-03 08:14

    This is covered in FAQ 1.1, 1.2 and 2.17.

    Some possibilities:

    DT[, keep, with = FALSE]
    DT[, c('V1', 'V3'), with = FALSE]
    DT[, c(1, 3), with = FALSE]
    DT[, list(V1, V3)]
    

    The reason DF[c('V1','V3')] works as it does for a data.frame is covered in ?`[.data.frame`

    Data frames can be indexed in several modes. When [ and [[ are used with a single vector index (x[i] or x[[i]]), they index the data frame as if it were a list. In this usage a drop argument is ignored, with a warning.


    From data.table 1.10.2, you may use the .. prefix when subsetting columns programmatically:

    When j is a symbol prefixed with .. it will be looked up in calling scope and its value taken to be column names or numbers [...] It is experimental.

    Thus:

    DT[ , ..keep]
    #    V1 V3
    # 1:  1  7
    # 2:  2  8
    # 3:  3  9
    
    0 讨论(0)
  • 2020-12-03 08:27

    Some more possibilities:

    DT[, .SD, .SDcols = keep]
    DT[, mget(keep)]
    
    0 讨论(0)
提交回复
热议问题