[英]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.