Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if date is a weekend or not (not using lubridate)

Tags:

I have a vector of date objects (yyyy-mm-dd) and I want to determine if any of them are on weekend or not. Is there a function that can determine this straightaway?

I can use wday() in the lubridate package and then determine if returned value is 01 or 07, but anything else more straightforward?

x <- seq(Sys.Date()-10, Sys.Date(), by = 1) x[lubridate::wday(x) %in% c(1, 7)] 
like image 632
DonDyck Avatar asked Oct 18 '14 15:10

DonDyck


People also ask

How do you find the day of the week from a date Lubridate?

wday() returns the day of the week as a decimal number or an ordered factor if label is TRUE .

What does Lubridate mean?

Lubridate is an R package that makes it easier to work with dates and times. Below is a concise tour of some of the things lubridate can do for you. Lubridate was created by Garrett Grolemund and Hadley Wickham, and is now maintained by Vitalie Spinu.

What is the use of Lubridate package?

lubridate: Make Dealing with Dates a Little EasierFunctions to work with date-times and time-spans: fast and user friendly parsing of date-time data, extraction and updating of components of a date-time (years, months, days, hours, minutes, and seconds), algebraic manipulation on date-time and time-span objects.


1 Answers

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 
like image 163
Rich Scriven Avatar answered Sep 28 '22 04:09

Rich Scriven