Creating factor variables 'weekend' and 'weekday' from date

Abhinav picture Abhinav · Mar 6, 2015 · Viewed 17.3k times · Source

I have the following dataframe. This is just the head and the dates span over a period of 2 months. My question is how can I create a new factor variable in the dataframe with two levels, "weekday" and "weekend", indicating whether a given date is a weekday or weekend day?

    steps        date      interval
1 37.3826  2012-10-01             0
2 37.3826  2012-10-01             5
3 37.3826  2012-10-01            10
4 37.3826  2012-10-01            15
5 37.3826  2012-10-01            20
6 37.3826  2012-10-01            25

Answer

akrun picture akrun · Mar 6, 2015

You can use base R

df1$date <- as.Date(df1$date)
#create a vector of weekdays
weekdays1 <- c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
#Use `%in%` and `weekdays` to create a logical vector
#convert to `factor` and specify the `levels/labels`
df1$wDay <- factor((weekdays(df1$date) %in% weekdays1), 
         levels=c(FALSE, TRUE), labels=c('weekend', 'weekday') 
#Or
df1$wDay <- c('weekend', 'weekday')[(weekdays(df1$date) %in% weekdays1)+1L]

Or isWeekday, isWeekend from timeDate. We can specify the weekdays with wday argument. It returns a logical vector, and if we need to convert to strings that can be possible as showed above.

library(timeDate)
isWeekday(df1$date, wday=1:5)