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

19,056

Solution 1

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)

Solution 2

What about this:

activity$week <- ifelse(weekdays(activity$date) %in% c("Saturday", "Sunday"), "weekend", "weekday")

Solution 3

using package chron, and assuming that your data.frame is called df:

df$weekend = chron::is.weekend(df$date)

the result is a column of boolean, TRUE when the date is in weekend (better to manipulate booleans here than strings)

Solution 4

Just thought I'd add a slightly more efficient answer using base, and taking advantage of the fact that both Saturday and Sunday are the only days starting with an "S":

df$Weekend <- grepl("S.+",weekdays(df$date))

Share:
19,056
Abhinav
Author by

Abhinav

Updated on June 11, 2022

Comments

  • Abhinav
    Abhinav almost 2 years

    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