通过存储在向量中的数字索引从数据表中提取列

Ama*_*ian 6 r indices data.table

我想从名为 dt 的数据表中提取第 4、5、6 列

以下方法有效:

    dt[, c(4,5,6)]
Run Code Online (Sandbox Code Playgroud)

但以下没有:

    a = c(4,5,6)
    dt[, a]
Run Code Online (Sandbox Code Playgroud)

事实上,第二种方法给了我一个结果:

    4 5 6
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么会这样吗?这两种方法看起来和我一样。

akr*_*run 7

我们可以..在对象 'a' 之前使用双点 ( ) 来提取列

dt[, ..a]
#   col4 col5 col6
#1:    4    5    6
#2:    5    6    7
#3:    6    7    8
#4:    7    8    9
Run Code Online (Sandbox Code Playgroud)

或者另一种选择是 with = FALSE

dt[, a, with = FALSE]
Run Code Online (Sandbox Code Playgroud)

数据

dt <- data.table(col1 = 1:4, col2 = 2:5, col3 = 3:6, col4 = 4:7, col5 = 5:8, col6 = 6:9)
Run Code Online (Sandbox Code Playgroud)

  • @Amazonian 你能告诉我 data.table 的 packageVersion .. 关于你的代码,如果你检查`?data.table`,`默认情况下 with=TRUE 并且 j 在 x 的框架内进行评估;列名可以用作变量。当 with=FALSE j 是列名称的字符向量、要选择的列位置的数字/逻辑向量或形式为 startcol:endcol 时,返回的值始终是 data.table。with=FALSE 通常在 data.table 中用于动态选择列。注意 x[, cols, with=FALSE] 等价于 x[, .SD, .SDcols=cols].` (2认同)