How to determine if date is a weekend or not (not using lubridate)
Another approach could be to use format
and %u
, which gives a number for the day of the week, starting with "1" representing "Monday".
With that, you can do:
x <- seq(as.Date("2014-10-18")-10, Sys.Date(), by = 1)
format(x, "%u") %in% c(6, 7)
# [1] FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE
x[format(x, "%u") %in% c(6, 7)]
# [1] "2014-10-11" "2014-10-12" "2014-10-18"
I put @AnandaMahto's suggestion here rather than a comment:
library(chron)
x <- seq(Sys.Date()-10, Sys.Date(), by = 1)
x[is.weekend(x)]
## [1] "2014-10-11" "2014-10-12" "2014-10-18"
You can use the base R function weekdays()
.
x <- seq(Sys.Date() - 10, Sys.Date(), by = 1)
weekdays(x, abbr = TRUE)
# [1] "Wed" "Thu" "Fri" "Sat" "Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"
x[grepl("S(at|un)", weekdays(x))]
# [1] "2014-10-11" "2014-10-12" "2014-10-18"
As far as lubridate goes, wday()
has a label
argument. When set to TRUE
, the (abbreviated) day names are returned instead of numbers. Use the abbr
argument to change to full names.
library(lubridate)
wday(x, label = TRUE)
# [1] Wed Thurs Fri Sat Sun Mon Tues Wed Thurs Fri Sat
# Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat