Reputation: 209
I have two data.tables on which I would like to create a third one as a soustraction of the two initials.
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)]) :
non-numeric argument to binary operator
Upvotes: 1
Views: 3497
Reputation: 1110
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
Upvotes: 0
Reputation: 887981
We can use with = FALSE
to extract the columns
Result[, (cols) := DT[, cols, with = FALSE]- DT_mirror[, cols, with= FALSE]]
Assuming the 'Result' is another data.table
created
Upvotes: 2