我想让它"自动"离开。无需在这部分代码中指定DR04
:mutate(across(DR1:DR04, ~.x + get(paste0(cur_column(), '_PV'))
.
library(dplyr)
library(tidyverse)
library(lubridate)
df1 <- structure(
list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28"),
date2 = c("2021-04-02","2021-04-02","2021-04-08","2021-04-08"),
Code = c("ABC","CDE","ABC","CDE"),
Week= c("Friday","Friday","Thursday","Thursday"),
DR1 = c(11,17,14,13),
DR01 = c(14,11,14,13), DR02= c(14,12,16,17),DR03= c(19,15,14,13),
DR04 = c(15,14,13,13)),
class = "data.frame", row.names = c(NA, -4L))
x<-df1 %>% select(starts_with("DR"))
x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
pk<-select(x, date2,Code, Week, DR1, ends_with("PV"))
med<-pk %>%
group_by(Code, Week) %>%
summarize(across(ends_with("PV"), median))
df1 %>%
inner_join(med, by = c('Code', 'Week')) %>%
mutate(across(DR1:DR04, ~.x + get(paste0(cur_column(), '_PV')),
.names = '{col}_{col}_PV')) %>%
select(date1:Week, DR1_DR1_PV:last_col())
date1 date2 Code Week DR1_DR1_PV DR01_DR01_PV DR02_DR02_PV DR03_DR03_PV DR04_DR04_PV
1 2021-06-28 2021-04-02 ABC Friday 11 11 11 11 11
2 2021-06-28 2021-04-02 CDE Friday 17 17 17 17 17
3 2021-06-28 2021-04-08 ABC Thursday 14 14 14 14 14
4 2021-06-28 2021-04-08 CDE Thursday 13 13 13 13 13
我们可以使用matches
df1 %>%
inner_join(med, by = c('Code', 'Week')) %>%
mutate(across(matches("^DR\d+$"), ~.x +
get(paste0(cur_column(), '_PV')),
.names = '{col}_{col}_PV')) %>%
select(date1:Week, DR1_DR1_PV:last_col())
与产出
date1 date2 Code Week DR1_DR1_PV DR01_DR01_PV DR02_DR02_PV DR03_DR03_PV DR04_DR04_PV
1 2021-06-28 2021-04-02 ABC Friday 11 11 11 11 11
2 2021-06-28 2021-04-02 CDE Friday 17 17 17 17 17
3 2021-06-28 2021-04-08 ABC Thursday 14 14 14 14 14
4 2021-06-28 2021-04-08 CDE Thursday 13 13 13 13 13
你可以试试
library(dplyr)
df1 %>%
inner_join(med, by = c('Code', 'Week')) %>%
mutate(across(-(date1:Week) & !matches("_PV"), ~.x + get(paste0(cur_column(), '_PV')),
.names = '{col}_{col}_PV')) %>%
select(date1:Week, DR1_DR1_PV:last_col())
返回
date1 date2 Code Week DR1_DR1_PV DR01_DR01_PV DR02_DR02_PV DR03_DR03_PV DR04_DR04_PV
1 2021-06-28 2021-04-02 ABC Friday 11 11 11 11 11
2 2021-06-28 2021-04-02 CDE Friday 17 17 17 17 17
3 2021-06-28 2021-04-08 ABC Thursday 14 14 14 14 14
4 2021-06-28 2021-04-08 CDE Thursday 13 13 13 13 13
我们"deselect"第一列(date1:Week
)和所有包含"_PV"
的列。