I have dataset of a full year of dates starting in September spanning a full 365 days:
dates
date | dayname | daytype |
---|---|---|
2022-09-01 | Thur | weekday |
2022-09-02 | Fri | weekday |
2022-09-03 | Sat | weekend/holiday |
2022-09-04 | Sun | weekend/holiday |
2022-09-05 | Mon | weekday |
I have run a ifelse line of code to assign weekdays or weekends/holidays:
dates$daytype <- ifelse(dates$dayname %in% c("Sat","Sun"), "weekend/holiday", "weekday")
My issue now is that some dates are holidays but cannot be defined that by an easy line of code like above. How can I change the daytype of holidays to reflect weekend/holiday in the daytype column.
The code I have tried is this but has an else factor I have to assign so I can't just change these dates I'm looking at:
daytype = case_when(
date %in% c(2022-09-05,2022-11-11,2022-11-24,2022-12-26,2023-01-02, 2023-1-16,2023-02-20,2023-05-14,2023-06-19,
202-07-04) ~ "Weekend/Holiday"))```
CodePudding user response:
You could use ifelse
again, e.g.
If dates is a character
-type:
dates$daytype <- ifelse(
dates$date %in% c("2022-09-05",
"2022-11-11",
"2022-11-24",
"2022-12-26",
"2023-01-02",
"2023-01-16",
"2023-02-20",
"2023-05-14",
"2023-06-19",
"2002-07-04"),
"Weekend/Holiday",
dates$daytype
)
If it is a date
-type:
dates$daytype <- ifelse(
dates$date %in% as.Date(c("2022-09-05",
"2022-11-11",
"2022-11-24",
"2022-12-26",
"2023-01-02",
"2023-01-16",
"2023-02-20",
"2023-05-14",
"2023-06-19",
"2002-07-04")),
"Weekend/Holiday",
dates$daytype
)
Output:
# A tibble: 5 × 3
date dayname daytype
<date> <chr> <chr>
1 2022-09-01 Thur weekday
2 2022-09-02 Fri weekday
3 2022-09-03 Sat weekend/holiday
4 2022-09-04 Sun weekend/holiday
5 2022-09-05 Mon Weekend/Holiday
Data:
library(readr)
dates <- read_table("date dayname daytype
2022-09-01 Thur weekday
2022-09-02 Fri weekday
2022-09-03 Sat weekend/holiday
2022-09-04 Sun weekend/holiday
2022-09-05 Mon weekday")