I'm working on a timestamp data frame. An excerpt of the date-related variables from the January sample of the data frame:
sample_dates <- data.frame(date = c("2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06", "2021-01-07", "2021-01-08", "2021-01-09", "2021-01-10", "2021-01-11", "2021-01-12", "2021-01-13", "2021-01-14", "2021-01-15", "2021-01-16", "2021-01-17", "2021-01-18", "2021-01-19", "2021-01-20", "2021-01-21", "2021-01-22", "2021-01-23", "2021-01-24", "2021-01-25", "2021-01-26", "2021-01-27", "2021-01-28", "2021-01-29", "2021-01-30", "2021-01-31"))
sample_dates <- sample_dates %>%
mutate(date = as.POSIXct(date)) %>%
mutate(day = factor(format(date, "%a")))
I want to add a new factor variable day_cat, the pseudo-code for which could be something like this:
sample_dates <- sample_dates %>%
# the month could start on any day and this function should identify it
# for the sample, I know January 2021 started on Friday
mutate(day_cat = while(month is not over)
if(day == "Fri") {"Fri1"},
else if(day == "Sat" | day == "Sun") {"Weekend1"},
else if(day == "Mon") {"Mon1"},
else if(day == "Tue" | day == "Wed" | day == "Thu") {"Weekdays1"},
# now we're onto the next Friday of the month
else if(day == "Fri") {"Fri2"},
else if(day == "Sat" | day == "Sun") {"Weekend2"},
else if(day == "Mon") {"Mon2"},
else if(day == "Tue" | day == "Wed" | day == "Thu") {"Weekdays2"},
...
...
# reached the end of month
)
mutate(day_cat = factor(day_cat, levels = c("Mon", "Weekdays", "Fri", "Weekend")))
So, the factors are Mon = {Mon}; Weekdays = {Tue, Wed, Thu}; Fri = {Fri}; Weekend = {Sat, Sun}. And, I want to number these factors as Mon1, Weekdays1, Fri1, Weekend1, Mon2, Weekdays2, Fri1, Weekend2, Mon3, and so on, in the day_cat variable (say if the month started from Monday).
The levels of the day_cat variable should be in the same order (for plotting purpose).
If a month starts on Wednesday, day_cat would take only that Wednesday and Thursday (the next day) as "Weekdays1". If the month ends on Saturday, day_cat would take only that Saturday as "Weekend4" or "Weekend5", whichever it might me.