How to use map from purrr with dplyr::mutate to create multiple new columns based on column pairs

前端 未结 8 711
無奈伤痛
無奈伤痛 2020-12-04 18:34

I have to following issue using R. In short I want to create multiple new columns in a data frame based on calculations of different column pairs in the data frame.

8条回答
  •  天涯浪人
    2020-12-04 19:24

    A slightly different approach using base R:

    cbind(df, lapply(unique(gsub("\\d+","", colnames(df))), function(li) {
       set_names(data.frame(V = apply(df[grep(li, colnames(df), val = T)], FUN = sum, MARGIN = 1)), paste0("sum_", li))
    }))
    #  a1 b1 c1 a2 b2 c2 sum_a sum_b sum_c
    #1  1  4 10  9  3 15    10     7    25
    #2  2  5 11 10  4 16    12     9    27
    #3  3  6 12 11  5 17    14    11    29
    #4  4  7 13 12  6 18    16    13    31
    #5  5  8 14 13  7 19    18    15    33
    

提交回复
热议问题