在R中绘制与动物园的月度时间序列

时间:2015-07-17 11:30:35

标签: r time-series

我将每日时间序列读作zoo,然后按月汇总时间序列以计算平均值:

# ts is the original daily time series
# ts is a zoo 
m = aggregate(ts, by=months, mean)

汇总日期m看起来像(这些值是伪造的):

April  August  December  February  January  July  
40      80       120     20        10       70  

June  March  May  November  October  September    
60    30     50   110       100      90


# Check the class of index
> class(index(m))
[1] "character"

# Subsetting manually
> m[c('January', 'December']
[1] December  January 
    120       10

显然,m的索引在内部按字符排序,这使得折线图难以阅读。

如何按月对汇总的时间序列m进行排序?

2 个答案:

答案 0 :(得分:2)

假设输入显示:

library(zoo)
ts <- zoo(1:12, as.Date(as.yearmon(2000) + 0:11/12))

aggregate(ts, by = match(months(index(ts)), month.name), mean)

请注意,month.name内置于R。

请确保您的问题具有可重现性。问题中的输入缺失。

答案 1 :(得分:0)

格洛腾德克的想法的另一个选择是

聚合(x,by = gsub(&#34; \ d \ d \ d \ d - (\ d \ d) - \ d \ d&#34;,&#34; \ 1&#34;,as .character(index(x))),mean)

当我尝试G.Grothendleck的原始代码时,我收到了一个错误,但也许我在创建测试数据时做错了

library(quantmod)
getQuote("APPL")
x <- as.zoo(x)
aggregate(x, by = match(months, month.name), mean)

制作人:

# Error in match(months, month.name) : 'match' requires vector arguments

但这有效

aggregate(x, by = gsub("\\d\\d\\d\\d-(\\d\\d)-\\d\\d", "\\1", as.character(index(x))), mean)