0

I have a bunch of dates in year-month-date format , trying to add a new column in the data frame that states if the date is a "weekday" or a "weekend" (either or).

I have to use mutate and lubridate. Tried using wday but not sure how to specify. Outcome should be something like the following:

date weekend_weekday 2023-02-15 weekday

How to format this in the code and which function to use?

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • https://lubridate.tidyverse.org/reference/day.html has everything you need to define weekday vs weekend day. After that the mutate is straightforward. – Paul Stafford Allen Feb 16 '23 at 07:44

1 Answers1

0

We can use lubridate::wday() and check if the date is 1 (Sunday) or 7 (Saturday):

library(dplyr)

dat <- tibble(id = 1:7,
              Date = Sys.Date() + id)

dat %>% 
  mutate(weekend = ifelse(wday(Date) %in% c(1,7), "weekend", "weekday"))
#> # A tibble: 7 x 3
#>      id Date       weekend
#>   <int> <date>     <chr>  
#> 1     1 2023-02-17 weekday
#> 2     2 2023-02-18 weekend
#> 3     3 2023-02-19 weekend
#> 4     4 2023-02-20 weekday
#> 5     5 2023-02-21 weekday
#> 6     6 2023-02-22 weekday
#> 7     7 2023-02-23 weekday

To be safe and not rely on the system options we should specify the week_start argument. If we set it to 1 the week starts at Monday, and we need to check if a date is 6 (Saturday) or 7 (Sunday):

dat %>% 
  mutate(weekend = ifelse(wday(Date, week_start = 1) >= 6,
                          "weekend", "weekday"))

#> # A tibble: 7 x 3
#>      id Date       weekend
#>   <int> <date>     <chr>  
#> 1     1 2023-02-17 weekday
#> 2     2 2023-02-18 weekend
#> 3     3 2023-02-19 weekend
#> 4     4 2023-02-20 weekday
#> 5     5 2023-02-21 weekday
#> 6     6 2023-02-22 weekday
#> 7     7 2023-02-23 weekday

Created on 2023-02-16 by the reprex package (v2.0.1)

TimTeaFan
  • 17,549
  • 4
  • 18
  • 39