减去两个data.tables

时间:2017-05-23 10:00:35

标签: r data.table

我有两个data.tables,我想创建第三个数据作为两个首字母的抽象。

library(data.table)
DT <- data.table(
  variable1 = c("a","b","c","d","e"),
  variable2 = 1:5,
  variable3 = c(1,2,5,6,8),
  variable4 = c(1,2,5,6,8),
  variable5 = c(1,2,5,6,8),
  variable6 = c(12,14,18,100,103),
  variable7 = c(0.02,0.02,0,0.02,0.02)
)
DT_mirror <- data.table(
  variable1 = c("a","b","c","d","e"),
  variable2 = 1:5,
  variable3 = c(2,2,4,6,8),
  variable4 = c(1,3,5,6,8),
  variable5 = c(1,2,6,6,8),
  variable6 = c(12,14,18,100,103),
  variable7 = c(0.02,0.02,0,0.02,0.02)
)
cols = sapply(DT, is.numeric)
cols = cols[-c(6,7)]
cols = names(cols)[cols]
for (vars in cols) Result[,(vars)] = eval(DT[,(vars)]) - eval(DT_mirror[,(vars)])
for (vars in cols) Result[,(vars)] = DT[,(vars)] - DT_mirror[,(vars)]

最后两行都会生成相同的错误消息。

  

eval中的错误(DT [,(vars)]) - eval(DT_mirror [,(vars)]):
      二元运算符的非数字参数

2 个答案:

答案 0 :(得分:2)

我们可以使用with = FALSE来提取列

Result[, (cols) := DT[, cols, with = FALSE]- DT_mirror[, cols, with= FALSE]]

假设&#39;结果&#39;是另一个data.table创建的

答案 1 :(得分:0)

我不知道这是否有用,但您可以使用矩阵:

 Results = as.data.table(as.matrix(DT[,-1])-as.matrix(DT_mirror[,-1]))


   variable2 variable3 variable4 variable5 variable6 variable7
1:         0        -1         0         0         0         0
2:         0         0        -1         0         0         0
3:         0         1         0        -1         0         0
4:         0         0         0         0         0         0
5:         0         0         0         0         0         0