Home > Software engineering >  Using a vector for conditions instead of individual lines in case_when(). Lubridate and Dplyr
Using a vector for conditions instead of individual lines in case_when(). Lubridate and Dplyr

Time:11-14

I have a column of dates that I would like to assign to the Sunday that week starts with.

For example: 11/01/2021 would be assigned to "Week of 10/31/2021" since it is between 10/31/2021 and 11/6/2021. While 11/10/2021 would be assigned to "Week of 11/07/2021" since it is between 11/07/2021 and 11/13/2021. Example:

library(lubridate)
library(tidyverse)
sunday_first <- "2021/10/31" %>% ymd()
sunday_last <-  "2021/11/28" %>% ymd()
list_weeks <- sunday_first   weeks(0:4)
list_days <- (sunday_first   days(0:30)) %>% enframe(value = "date")

list_days %>% mutate("Week of" = case_when(
                                  between(date, list_weeks[1], list_weeks[1]   6) ~ list_weeks[1],
                                  between(date, list_weeks[2], list_weeks[2]   6) ~ list_weeks[2],
                                  between(date, list_weeks[3], list_weeks[3]   6) ~ list_weeks[3],
                                  between(date, list_weeks[4], list_weeks[4]   6) ~ list_weeks[4])

)

How can I do something like this for multiple years without so many lines of code in the case_when statement? Spiritually what I am looking for is how to go through a vector of conditions. Something like this:

list_days %>% mutate("Week of" = case_when(
                                  between(date, list_weeks[i], list_weeks[i]   6) ~ list_weeks[i])
)

CodePudding user response:

If you just want to figure out what the week is, use this function

weekOf <- function(date){
  days_after_sunday = wday(date)
  return(as.Date(date)-days(days_after_sunday-1))
}

week_str <- paste("Week of ", weekOf(Sys.Date()))

This returns Week of 2021-11-07

CodePudding user response:

Could you use floor_date from lubridate and include week for unit? The default for week_start is 7 (or Sunday) so you could omit that argument.

library(lubridate)

list_days <- as.Date(c("2021-11-01", "2021-11-10"))

floor_date(list_days, unit = 'week')

Output

[1] "2021-10-31" "2021-11-07"
  • Related