如何用dplyr批量将同后缀Monday列减去对应Tuesday列?
用dplyr批量实现Monday列减对应Tuesday列的需求
需求说明
需要将数据框中每个Monday_N列的值减去对应的Tuesday_N列的值,最终保留Monday_N的列名并移除所有Tuesday_*列,且需适配列数较多的场景,无需手动逐个指定列计算。
示例数据集
df <- structure(list(id = 1:7, Monday_1 = c(4L, 11L, 18L, 6L, 20L, 5L, 12L), Monday_2 = c(20L, 3L, 20L, 12L, 1L, 10L, 15L), Monday_3 = c(14L, 20L, 8L, 17L, 4L, 2L, 3L), Monday_4 = c(13L, 8L, 11L, 3L, 12L, 14L, 17L), Tuesday_1 = c(1L, 14L, 7L, 16L, 2L, 6L, 12L), Tuesday_2 = c(10L, 8L, 1L, 16L, 10L, 13L, 9L), Tuesday_3 = c(4L, 9L, 9L, 8L, 7L, 9L, 12L), Tuesday_4 = c(12L, 18L, 3L, 18L, 6L, 11L, 8L)), class = "data.frame", row.names = c(NA, -7L))
dplyr解决方案
library(dplyr) library(stringr) result_df <- df %>% # 批量处理所有Monday列,减去对应Tuesday列 mutate(across( .cols = starts_with("Monday_"), .fns = ~ .x - get(str_replace(cur_column(), "Monday", "Tuesday")), .names = "{col}" # 保留原Monday列名 )) %>% # 移除所有Tuesday列 select(-starts_with("Tuesday_"))
代码解释
across(starts_with("Monday_"), ...):选中所有以Monday_开头的列,实现批量处理str_replace(cur_column(), "Monday", "Tuesday"):将当前处理的Monday_N列名替换为对应的Tuesday_N,再通过get()获取该列的值~ .x - get(...):完成当前Monday列与对应Tuesday列的差值计算.names = "{col}":确保计算后的列仍保留原Monday_N的名称select(-starts_with("Tuesday_")):移除所有以Tuesday_开头的列,得到最终结果
验证结果
运行上述代码后,result_df的输出如下:
id Monday_1 Monday_2 Monday_3 Monday_4 1 1 3 10 10 1 2 2 -3 -5 11 -10 3 3 11 19 -1 8 4 4 -10 -4 9 -15 5 5 18 -9 -3 6 6 6 -1 -3 -7 3 7 7 0 6 -9 9
内容的提问来源于stack exchange,提问作者887
相关产品推荐
相关产品推荐

