Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 863
Abhinav Avatar asked Mar 06 '15 06:03

Abhinav


3 Answers

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)
like image 120
akrun Avatar answered Sep 23 '22 17:09

akrun


What about this:

activity$week <- ifelse(weekdays(activity$date) %in% c("Saturday", "Sunday"), "weekend", "weekday")
like image 43
f0nzie Avatar answered Sep 20 '22 17:09

f0nzie


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)

like image 44
RockScience Avatar answered Sep 20 '22 17:09

RockScience