Divide the xts object by given irregular intervals in R

I want to divide the daily xts object into 4 weeks, which correspond to the following days of the month: 1st, 8th-14th, 15th-21st and 22nd until the end of the month, where last week usually longer (but that's fine!).

Here is an example code for the xts object code 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 problem is that January 1 does not happen on Sunday, so split.xts does not necessarily do what I want.

Initially, I thought that I could create four intervals corresponding to the days noted above, however I do not know if this is correct.

Is there a way to break an xts object into the intervals you create?

+5
source share
1 answer

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

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

All Articles