0

I am trying to split a time series data of oil prices spanning 35 years at particular year. For example, all data up to 2018 into one series and later data into another. Can I use the split() function to do the same? More details about the time series below.

 > str(myxts)
  An ‘xts’ object on 1986-01-15/2020-09-15 containing:
  Data: num [1:417, 1] 22.9 15.5 12.6 12.8 15.4 ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  

Thanks in advance.

Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36

1 Answers1

0

This creates an xts object from 2000/1/1 to 2002/9/26 and then splits it into everything up to the end of year 2000 and everything from 2001 onwards.

tt <- seq(as.Date("2000-01-01"), by = "day", length = 1000)
x <- xts(seq_along(tt), tt)
range(time(x))
## [1] "2000-01-01" "2002-09-26"

s <- split(x, as.yearmon(time(x)) >= 2001)

range(time(s[[1]]))
## [1] "2000-01-01" "2000-12-31"

range(time(s[[2]]))
## [1] "2001-01-01" "2002-09-26"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • The output of the split function was a list of zoo objects which I had to convert back to xts. Nevertheless it worked for me. Thank you!! – user14607313 Nov 09 '20 at 19:32
  • The question did not specify the output other than it should be two series. `lapply(s, as.xts)` would convert each series to xts. – G. Grothendieck Nov 09 '20 at 22:21