Home > Enterprise >  Make the code understand the day of the week from the chosen date
Make the code understand the day of the week from the chosen date

Time:10-10

The executable code below works normally, as you can see. Note that for m, I'm specifying Week and Code. For Week, I specify it as Friday since I chose dmda as 16/07, which is a Friday. However, I would like to know if it's possible, to make the code understand that 16/07 is a Friday, and I don't specify in m Week == "Friday".

library(dplyr)

df <- structure(
  list(date = c("2021-06-30","2021-06-30","2021-07-07","2021-07-07","2021-07-09","2021-07-09","2021-07-09","2021-07-16"),
       Code = c("ABC","BCD","ABC","BCD","DCE","CDE","DCE","CDE"),
       Week= c("Wednesday","Wednesday","Wednesday","Wednesday","Friday","Friday","Friday","Friday"),
       DR1 = c(4,1,4,3,3,4,3,5)),
  class = "data.frame", row.names = c(NA, -8L))

dmda<-"2021-07-16"
CodeChosse<-"CDE"

m<-df %>%
  group_by(Code,Week) %>%
  summarize(across(starts_with("DR1"), mean))
> m
# A tibble: 4 x 3
# Groups:   Code [4]
  Code  Week        DR1
  <chr> <chr>     <dbl>
1 ABC   Wednesday   4  
2 BCD   Wednesday   2  
3 CDE   Friday      4.5
4 DCE   Friday      3  

m<-subset(m, Week == "Friday" & Code == CodeChosse)$DR1
> m
[1] 4.5

CodePudding user response:

You may use match -

m <- subset(m, Week == df$Week[match(dmda, df$date)] & Code == CodeChosse)$DR1
m
#[1] 4.5

CodePudding user response:

We may do this with tidyverse

library(dplyr)
m <- m %>%
        filter(Week %in% df$Week[match(dmda, df$date)], Code == CodeChoose)$DR1
  •  Tags:  
  • r
  • Related