I have a data.table
, dt:
dt
Id v1 v2 v3 x1 x2 x3
1 7 1 3 5 6 8
2 1 3 5 6 8 5
3 3 5 6 8 5 1
v1, v2, v3 an
You can use set
in the loop.
library(data.table)
DT <- fread('Id v1 v2 v3 x1 x2 x3
1 7 1 3 5 6 8
2 1 3 5 6 8 5
3 3 5 6 8 5 1')
for (i in 1:3) {
set(DT,j=paste0("Diff_",i),value = DT[[paste0("v",i)]]-DT[[paste0("x",i)]])
}
DT
#> Id v1 v2 v3 x1 x2 x3 Diff_1 Diff_2 Diff_3
#> 1: 1 7 1 3 5 6 8 2 -5 -5
#> 2: 2 1 3 5 6 8 5 -5 -5 0
#> 3: 3 3 5 6 8 5 1 -5 0 5
Created on 2020-05-27 by the reprex package (v0.3.0)