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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With