问题
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