R: splitting long zoo time series into calendar

半腔热情 提交于 2020-01-04 06:32:16

问题


I have a several-year length zoo object.

This is a time series of daily quotes (first column : date, second column : quote)

I wish to split this long time series into calendar year subsets, the ultimate goal being to plot those data in a single chart, the horizontal axis of which being one year-length.

(I don't want to convert my source daily data into monthly ones or any other timestep ...).

Thank you.


回答1:


Here's one way

library(quantmod)
getSymbols("SPY", src='yahoo', from='2000-01-01', to='2012-01-01')
SPY <- as.zoo(Ad(SPY))
# Now I have zoo data with a single value for each day (like you say you have)
# Convert it to xts so that I can use xts' split method
mydata <- as.xts(SPY)
# Split data by years.  Give them rownames that are day of year instead of 
# specific dates. cbind data together and plot
ts.plot(do.call(cbind, lapply(split(mydata, 'years'), function(x) {
  zoo(x, 1:NROW(x))
})), col=rainbow(nyears(mydata)))

Alternatively,

tapply(SPY, format(index(SPY), "%Y"), c)

will split by year and does not require converting to xts



来源:https://stackoverflow.com/questions/9762220/r-splitting-long-zoo-time-series-into-calendar

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