Multiple pairwise differences based on column name patterns

后端 未结 3 1178
悲哀的现实
悲哀的现实 2021-01-15 02:31

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

3条回答
  •  离开以前
    2021-01-15 02:44

    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)

提交回复
热议问题