R Subset XTS weekdays

后端 未结 2 1132
予麋鹿
予麋鹿 2021-02-05 16:23

How do I subset an xts object to only include weekdays (Mon-Fri, with Saturday and Sunday excluded)?

2条回答
  •  有刺的猬
    2021-02-05 16:53

    By computing the day-of-the week given the date, and subsetting. In the example, I use a Date type but the cast to POSIXlt works the same way for POSIXct intra-day timestamps.

    > mydates <- Sys.Date() + 0:6
    > mydates
    [1] "2012-01-31" "2012-02-01" "2012-02-02" "2012-02-03" "2012-02-04" 
    +   "2012-02-05" "2012-02-06"
    > we <- sapply(mydates, function(d) { as.POSIXlt(d)$wday}) %in% c(0, 6)
    > we
    [1] FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
    > mydates[ ! we ]
    [1] "2012-01-31" "2012-02-01" "2012-02-02" "2012-02-03" "2012-02-06"
    > 
    

    This really is not an xts question but basic date handling.

提交回复
热议问题