Ziwei Ziwei - 3 months ago 7
R Question

how to convert the weekdays to a factor in R

I have a data frame like this:

date count wd
2012-10-01 0 Monday
2012-10-02 5 Tuesday
2012-10-06 10 Saturday
2012-10-07 15 Sunday


I use

dat <- mutate(dat,wd = weekdays(as.Date(dat$date)))


to add a new array "wd" , however, I'd like to add a new factor array to show if this day is a weekday or weekend, something like:

date count wd
2012-10-01 0 weekday
2012-10-02 5 weekday
2012-10-06 10 weekend
2012-10-07 15 weekend


Is any simple way to do that? Thanks

Answer

ifelse is that standard way to check a condition on each element of a vector and do something based on the check. Since you already have the named weekdays, you have a pretty trivial condition to check:

dat$we = ifelse(dat$wd %in% c("Saturday", "Sunday"), "weekend", "weekday")

This adds a new variable, we, to your data. It will be a factor by default when added to the data frame with $<-.

You can, of course, use ifelse() inside mutate (or use dplyr::if_else), in which case you would need to wrap the result in factor() to coerce it to a factor - it will be a character by otherwise.


For other methods of checking weekendness that don't depend on already having the names of the days of the week see How to check if a date is a weekend?.