Home > Mobile >  How recognize weekday depending on entry date
How recognize weekday depending on entry date

Time:12-22

I have a simple question, but I wanted to know how to do it: I have a database and two input data (dmda and DTest):

df1 <- structure(
  list(date = c("2021-06-23","2021-06-24","2021-06-30","2021-07-01"),
       DTT= c("Hol","Hol","Hol",0),
       Week= c("Wednesday","Thursday","Wednesday","Thursday"),
       Category = c("ABC","FDE","ABC","FDE"),
       DR01 = c(4,1,2,3), DR02= c(4,2,0,2),DR03= c(9,5,0,1),
       DR04 = c(5,4,3,2),DR05 = c(5,4,0,2)),
  class = "data.frame", row.names = c(NA, -4L))
   
  dmda<-"2021-07-01"
    DTest <-"0"

df2<-df1%>%
group_by(Category,Week, DTT) %>%
summarize(across(starts_with("DR"), median),.groups = 'drop')

> df2
# A tibble: 3 x 8
  Category Week      DTT    DR01  DR02  DR03  DR04  DR05
  <chr>    <chr>     <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 ABC      Wednesday Hol       3     2   4.5     4   2.5
2 FDE      Thursday  0         3     2   1       2   2  
3 FDE      Thursday  Hol       1     2   5       4   4 

If I want to make an if condition I can do it like this:

if(any(df2$DTT == DTest & df2$Week == "Thursday" , na.rm = TRUE)) {
....
}

Now my doubt is that I didn't want to use df2$Week == "Thursday" but rather use dmda that was defined. In other words, is there any way, from the date I chose in dmda, for the code to identify what day of the week it is?

CodePudding user response:

We could convert the 'dmda' to Date class and extract the weekday with format (%A) - which is specified in the ?strptime documentation

%A - Full weekday name in the current locale. (Also matches abbreviated name on input.)

wkday <- format(as.Date(dmda), "%A")
wkday
[1] "Thursday"

and then use that in the if loop

if(any(df2$DTT == DTest & df2$Week == wkday , na.rm = TRUE)) {
....
}
  •  Tags:  
  • r
  • Related