按索引

时间:2018-01-17 18:35:07

标签: r data.table

我无法理解为什么以下不起作用:

library(data.table)
dt <- as.data.table(mtcars) 
colnum <- grep("disp", tolower(colnames(dt)))
# 3

dt[, colnum, with = F] <- dt[, colnum, with = F]*2

以上引发了错误:

Error in `[<-.data.table`(`*tmp*`, , colnum, with = F, value = list(disp = c(320,  : 
  unused argument (with = F)

删除第二个术语with = F也会输出错误:

dt[, colnum, with = F] <- dt[, colnum] * 2

Error in `[.data.table`(q, , colnum) : 
  j (the 2nd argument inside [...]) is a single symbol but column name 'colnum' is not found. 
Perhaps you intended DT[,..colnum] or DT[,colnum,with=FALSE]. 
This difference to data.frame is deliberate and explained in FAQ 1.1.

为什么这不起作用?以上只是一个简化示例,但我想在data.table列上执行更复杂的操作。

1 个答案:

答案 0 :(得分:3)

data.table - 执行此操作的方式为updating by reference,如下所示:

 dt[, (colnum) := lapply(.SD, '*', 2), .SDcols = colnum][]

给出:

     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
 1: 21.0   6 320.0 110 3.90 2.620 16.46  0  1    4    4
 2: 21.0   6 320.0 110 3.90 2.875 17.02  0  1    4    4
 3: 22.8   4 216.0  93 3.85 2.320 18.61  1  1    4    1
 4: 21.4   6 516.0 110 3.08 3.215 19.44  1  0    3    1
 5: 18.7   8 720.0 175 3.15 3.440 17.02  0  0    3    2
 6: 18.1   6 450.0 105 2.76 3.460 20.22  1  0    3    1
.....

您可以在Getting started页面上找到更多信息。