Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split xts object by specified irregular intervals in R

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?

like image 742
SAMIR SULTANI Avatar asked Jul 18 '15 13:07

SAMIR SULTANI


1 Answers

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)
like image 145
Joshua Ulrich Avatar answered Oct 14 '22 07:10

Joshua Ulrich