[英]Subtract two data.tables
I have two data.tables on which I would like to create a third one as a soustraction of the two initials. 我有两个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)]
Both last lines generate the same error message. 最后两行都生成相同的错误消息。
Error in eval(DT[, (vars)]) - eval(DT_mirror[, (vars)]) :
eval(DT [,(vars)])-eval(DT_mirror [,(vars)])中的错误:
non-numeric argument to binary operator二进制运算符的非数字参数
We can use with = FALSE
to extract the columns 我们可以使用
with = FALSE
来提取列
Result[, (cols) := DT[, cols, with = FALSE]- DT_mirror[, cols, with= FALSE]]
Assuming the 'Result' is another data.table
created 假设“结果”是另一个
data.table
创建
I don't know if this can help, but you can work with matrixes: 我不知道这是否有帮助,但是您可以使用矩阵:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.