簡體   English   中英

在R中與動物園繪制每月時間序列

[英]Plot monthly time series with zoo in R

我將每天的時間序列讀為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

假設顯示輸入:

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中。

請確保您的問題是可重復的。 問題中的輸入缺失。

G. Grothendleck的想法的另一個選擇是

合計(x,by = gsub(“ \\ d \\ d \\ d \\ d-(\\ d \\ d)-\\ d \\ d”,“ \\ 1”,as.character(index(x))),均值)

當我嘗試使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM