2012-05-29 36 views
3

我發現的大多數包和帖子都適用於固定大小窗口或累計月/週數據。是否有可能計算滾動K月平均值?如何計算R中過去1個月的滾動平均值

例如,對於1個月滾動窗口,假設數據是:

Date   Value 
2012-05-28 101 
2012-05-25  99 
2012-05-24 102 
.... 
2012-04-30  78 
2012-04-27  82 
2012-04-26  77 
2012-04-25  75 
2012-04-24  76 

前三滾動1個月窗口應該是:

1. 2012-05-28 to 2012-04-30 
2. 2012-05-25 to 2012-04-26 
3. 2012-05-24 to 2012-04-25 

請注意,這不是固定寬度的滾動窗口。窗口實際上每天都在變化。

非常感謝先進!

+1

查看'zoo'包中的'rollmean'。 – Justin

+0

看這裏:http://stackoverflow.com/q/743812/602276 – Andrie

+1

感謝您的快速回復。但這些僅適用於固定滾動窗口。 – StanFish

回答

1

我用這段代碼根據每日價格數據計算每月平均值。

#function for extracting month is in the lubridate package 
install.packages(c("plyr", "lubridate")) 
require(plyr); require(lubridate) 

#read the daily data 
daily = read.csv("daily_lumber_prices.csv") 
price = daily$Open 
date = daily$Date 

#convert date to a usable format 
date = strptime(date, "%d-%b-%y") 
mon = month(date) 
T = length(price) 

#need to know when months change 
change_month = rep(0,T) 

for(t in 2:T){ 
    if(mon[t] != mon[t-1]){ 
    change_month[t-1] = 1 
    } 
} 

month_avg = rep(0,T) 
total = 0 
days = 0 

for(t in 1:T){ 
    if(change_month[t] == 0){ 
    #cumulative sums for each variable 
    total = total + price[t] 
    days = days + 1 
    } 

    else{ 
    #need to include the current month in the calculation 
    month_avg[t] = (total + price[t])/(days + 1) 
    #reset the variables 
    total = 0 
    days = 0 
    } 
} 

因此,變量month_avg是存儲每月平均值。

是這樣的嗎?這段代碼說明了可變的月份長度。確實有更高效的方式來做到這一點,但這是有效的!