Select a sequence of columns: `:` works but not `seq`

前端 未结 3 424
旧巷少年郎
旧巷少年郎 2020-12-11 17:00

I\'m trying to subset a dataset by selecting some columns from a data.table. However, my code does not work with some variations.

Here is a sample data.table

3条回答
  •  半阙折子戏
    2020-12-11 17:09

    The lesson I learned is to use list instead of c:

     DT[ ,list(ID,Capacity)]
     #---------------------------
         ID Capacity
      1:  1      483
      2:  2      703
      3:  3      924
      4:  4      267
      5:  5      588
     ---            
    196: 46      761
    197: 47      584
    198: 48      402
    199: 49      416
    200: 50      130
    

    It lets you ignore those pesky quotations, and it also moves you in the direction of seeing the j argument as an evaluated expression with an environment of the datatable itself.

    To 'get' the named columns by number use the mget function and the names function. R 'names' are language elements, i.e., data objects in the search path from the current environment. Column names of dataframes are not actually R names. So you need a function that will take a character value and cause the interpreter to consider it a fully qualified name. Datatable-[-function syntax for the j item does handle column names as language objects rather than character values as would the [.data.frame-function:

    DT[ ,mget(names(DT)[c(1,2)])]
         ID Capacity
      1:  1      483
      2:  2      703
      3:  3      924
      4:  4      267
      5:  5      588
     ---            
    196: 46      761
    197: 47      584
    198: 48      402
    199: 49      416
    200: 50      130
    

提交回复
热议问题