I have a function that basically filters an SPV row, as you can see below. Note that I do return_coef <- function(df1, idd,dmda, CategoryChosse) { However, I would not like df1 as an argument of the function, but rather the attributes of the df1 dataset, which in this case is Id, date1, Week, Category, DR1 and DRM. How can I adjust this?
library(dplyr)
library(tidyr)
library(lubridate)
df1 <- structure(
list(
Id = c(1, 1, 1, 1),
date1 = c("2022-01-06","2022-01-06","2022-01-06","2022-01-06"),
date2 = c("2022-01-02","2022-01-03","2022-01-09","2022-01-10"),
Week = c("Sunday","Monday","Sunday","Monday"),
Category = c("EFG", "ABC","EFG","ABC"),
DR1 = c(200, 300, 200, 200),
DRM0 = c(300, 300, 300, 300),
DRM01 = c(300, 300, 300, 300),
DRM02 = c(300,300,300,300),
DRM03 = c(300,300,300,300),
DRM04 = c(300,250,350,350)),row.names = c(NA, 4L), class = "data.frame")
return_coef <- function(df1, idd,dmda, CategoryChosse) {
x<-df1 %>% select(starts_with("DRM0"))
x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
PV<-select(x,Id, date2,Week, Category, DR1, ends_with("PV"))
med<-PV %>%
group_by(Id,Category,Week) %>%
dplyr::summarize(dplyr::across(ends_with("PV"), median))
SPV<-df1%>%
inner_join(med, by = c('Id','Category', 'Week')) %>%
mutate(across(matches("^DRM0\\d+$"), ~.x +
get(paste0(cur_column(), '_PV')),
.names = '{col}_{col}_PV')) %>%
select(Id:Category, DRM01_DRM01_PV:last_col())
SPV <- SPV %>%
filter(Id==idd,date2 == dmda, Category == CategoryChosse)
return(SPV)
}
return_coef(df1, "1", "2022-01-10", "ABC")
`summarise()` has grouped output by 'Id', 'Category'. You can override using the `.groups` argument.
Id date1 date2 Week Category DRM01_DRM01_PV DRM02_DRM02_PV DRM03_DRM03_PV DRM04_DRM04_PV
1 1 2022-01-06 2022-01-10 Monday ABC 250 250 250 300