【问题标题】:How to calculate rolling average of past 1 month in R如何在R中计算过去1个月的滚动平均值
【发布时间】:2012-06-03 21:42:39
【问题描述】:

我发现大多数包和帖子都适用于固定大小的窗口或汇总的月/周数据。是否可以计算滚动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

前三个滚动的 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

请注意,这不是固定宽度的滚动窗口。窗口实际上每天都在变化。

【问题讨论】:

标签: r window time-series


【解决方案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 存储了每月平均值。

是这样的吗?此代码说明了月份的可变长度。当然有一种更有效的方法,但这很有效!

【讨论】:

    【解决方案2】:

    假设您的数据框是 df 这对我有用:

    df$past_avg = sapply(df$Date, function(i){
        i = as.POSIXct(i)
        mean(subset(df, Date > (i - months(1)) & Date < i)$Value)
    })
    

    仅使用基数 R。您可以通过更改 months() 中的值来调整到过去多少个月。

    【讨论】:

      【解决方案3】:

      runner 包完全支持不规则间隔时间序列上的滚动窗口操作。要计算 x 对象的 1 个月 移动平均线,必须指定 idx = date(使跑步者与时间相关)和 k = "1 months"k = 30(天),具体取决于更重要的是什么给用户。用户可以apply any R function - 在这种情况下我们执行mean

      # example data
      x <- cumsum(rnorm(20))
      date <- Sys.Date() + cumsum(sample(1:5, 20, replace = TRUE)) # unequaly spaced time series
      
      # calculate rolling average
      runner::runner(
        x = x, 
        k = "1 months", 
        idx = date, 
        f = mean
      )
      

      【讨论】:

        猜你喜欢
        • 2019-03-03
        • 1970-01-01
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        • 2021-08-18
        • 2015-04-24
        • 1970-01-01
        相关资源
        最近更新 更多