Split xts object by specified irregular intervals in R

旧城冷巷雨未停 提交于 2019-12-10 13:11:28

问题


I want to split a daily xts object into 4 separate weeks which correspond to the following days in the month: 1st-7th, 8th-14th, 15th-21st, and 22nd to the end of the month, where the last week will generally be longer (but that's okay!).

Here's some example code of an xts object for January 2004 created from a sequence of dates:

week <- seq(from=as.Date("2004-01-01"), to=as.Date("2004-01-31"), by = "day")
x2 <- sample(1:50, 31) # generating 31 random numbers 
January_series <- xts(x2, order.by=week) # create January daily series 

The issue is that January 1st doesn't occur on a Sunday so split.xts doesn't necessarily do what I want.

I initially thought that I could create four intervals corresponding to those days noted above however I don't know whether that is the right approach.

Is there any way of splitting an xts object by intervals which you've created?


回答1:


You can use .indexmday to get the day of the month for each observation in your xts object. Then use cut to define the intervals you want to split by.

intervals <- cut(.indexmday(January_series), c(0,7,14,21,31), paste0("W",1:4))
splitlist <- split(January_series, intervals)


来源:https://stackoverflow.com/questions/31491490/split-xts-object-by-specified-irregular-intervals-in-r

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