R Subset XTS weekdays

回眸只為那壹抹淺笑 提交于 2019-12-20 12:08:55

问题


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


回答1:


Here's what I'd do:

library(xts)
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
x <-  sample.xts['2007']  
x[!weekdays(index(x)) %in% c("Saturday", "Sunday")]

EDIT: Joshua Ulrich in comments points out a better solution using .indexwday(), one of a family of built-in accessor functions for extracting pieces of the index of xts class objects. Also, like Dirk Eddelbuettel's solution, the following should be locale-independent:

x[.indexwday(x) %in% 1:5]



回答2:


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.



来源:https://stackoverflow.com/questions/9088116/r-subset-xts-weekdays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!