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
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)
What about this:
activity$week <- ifelse(weekdays(activity$date) %in% c("Saturday", "Sunday"), "weekend", "weekday")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With