我正在使用R,試圖找出每年有4個季度數據的平均值。R中每年屬於平均季度
我首先從在線抓取數據,將數據轉換爲時間序列對象,選擇我想要的時間幀,轉換爲一個xts對象,然後使用apply.yearly()
函數。
library(rvest)
library(xts)
library(magrittr)
inflation <- html("http://www.bankofcanada.ca/rates/indicators/capacity-and-inflation-pressures/inflation/historical-data/")
data1 <- inflation %>%
html_nodes("td:nth-child(2)") %>%
html_text() %>%
as.numeric() %>%
rev() %>% #reverses the order of the vector
na.omit() %>%
ts(frequency = 4, start = c(1993,1))`
clean_canada <- window(data1, 2000, c(2014,4)) %>% #selects a window starting at 2000, ending at period 4 of 2014
as.xts() %>%
apply.yearly(mean)
但是,這看起來會產生每4個季度的滾動平均值,而不是每個日曆年產生一個平均值。任何人都知道修復?
也許這有助於'窗口(DATA1,2000,C(2014,4))%>%as.xts()%>%as.data.frame()%>%GROUP_BY(GRP = (%)%>%summary(Mean = mean(V1))' – akrun
如果你想要年平均值,'window(data1,2000,c(2014,4))%>%as.xts()% >%as.data.frame()%>%group_by(grp = sub('\\ s +。*','',row.names(。)))%>%summarize(Mean = mean(V1))' – akrun