如何计算R中过去1个月的滚动平均值

Alp*_*pha 5 r window time-series

我发现的大多数软件包和帖子均适用于固定大小的窗口或月/周汇总数据。可以计算滚动k个月的平均值吗?

例如,对于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
Run Code Online (Sandbox Code Playgroud)

前三个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
Run Code Online (Sandbox Code Playgroud)

请注意,这不是固定宽度的滚动窗口。该窗口实际上每天都会更改。

wca*_*ell 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
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,变量month_avg 存储每月平均值。

是这样的吗?此代码考虑了月份的可变长度。当然有一种更有效的方法来做到这一点,但这确实有效!