Remove weekend data in a dataframe

前端 未结 3 773
失恋的感觉
失恋的感觉 2020-12-03 12:32

As you can see from the dataframe below, RBloomberg returns NAs for weekend dates.

I want to remove the entire row if it falls on a weekend. How would I do this?

相关标签:
3条回答
  • 2020-12-03 13:02

    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.

    0 讨论(0)
  • 2020-12-03 13:03

    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'))
    
    0 讨论(0)
  • 2020-12-03 13:14

    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

    0 讨论(0)
提交回复
热议问题