I would like to leave it "automatically" without having to specify DR04
in this part of the code: 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
CodePudding user response:
You could try
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())
which returns
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
We "deselect" the first columns (date1:Week
) and every column containing "_PV"
.
CodePudding user response:
We may use 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())
-output
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