简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM