Multiple pairwise differences based on column name patterns

后端 未结 3 1181
悲哀的现实
悲哀的现实 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 03:03

    You could split by whether the column contains x and then take the difference of the resulting data tables.

    new_cols <- 
      do.call('-', split.default(dt[,-1], grepl('x', names(dt)[-1])))
    
    dt[, paste0('diff', seq_along(new_cols)) := new_cols]
    
    dt
    #    Id v1 v2 v3 x1 x2 x3 diff1 diff2 diff3
    # 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
    

    Or using similar logic to the code snippet in the question you could do

    newnames <- paste0("diff",1:3)
    v <- paste0("v",1:3)
    x <- paste0("x",1:3)
    
    dt[, (newnames) := Map('-', mget(v), mget(x))]
    
    dt
    #    Id v1 v2 v3 x1 x2 x3 diff1 diff2 diff3
    # 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
    

提交回复
热议问题