Remove weekend data in a dataframe

Convert the date column to a POSIXlt ,eg

date <- as.POSIXlt(date,format="%Y-%m-%d")

Then you can access the day of the week using

date$wday

and subset the frame appropriately


The answer by blindJesse is correct and useful as it falls back to base R functions.

Many packages have additional helper wrappers. Here is one from timeDate which requires conversion to its type:

R> isWeekend( as.timeDate( seq( as.Date("2011-01-01"), 
+                               to=as.Date("2011-01-07"), by=1 ) ) )
2011-01-01 2011-01-02 2011-01-03 2011-01-04 2011-01-05 2011-01-06 2011-01-07  
      TRUE       TRUE      FALSE      FALSE      FALSE      FALSE      FALSE  
R> 

and here is another approach using a function from RcppBDT:

R> sapply(seq(as.Date("2011-01-01"),to=as.Date("2011-01-07"), by=1),getDayOfWeek)
[1] 6 0 1 2 3 4 5
R> 
R> sapply(seq(as.Date("2011-01-01"),to=as.Date("2011-01-07"), by=1),getDayOfWeek)
+         %%6 == 0
[1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
R> 

The lubridate package also has wday() and there are undoubtedly more he;per functions in other packages.


For completeness' sake, I would add to blindjesse's answer that typing ?weekdays reveals that R has base functions weekdays(), months() and quarters() that work on both the posix and date types, and are I believe vectorized, so this would work as well:

!(weekdays(as.Date(date)) %in% c('Saturday','Sunday'))

Tags:

Date

R

Weekend