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

6

大多数我找到的软件包和帖子都是针对固定大小的窗口或整个月/周数据进行平均处理。是否可以计算滚动的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. 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
请看这里:https://dev59.com/4HRB5IYBdhLWcg3wCjYV - Andrie
1
谢谢您的快速回复。但是,这些仅适用于固定滚动窗口。 - Alpha
2
你是如何定义一个月的?是往回看30天吗?还是往回看到上个月的同一天?我不确定窗口宽度是如何变化的,不太理解。 - Justin
显示剩余8条评论
3个回答

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存储了每月的平均值。

是这样吗?这段代码考虑了月份长度的变量。肯定有更有效率的方法,但这个也能用!


0

runner包完全支持在不规则时间序列上进行滚动窗口操作。要计算x对象的1个月移动平均值,用户必须指定idx = date(使运行器与时间相关)和k = "1 months"k = 30(天),具体取决于用户的需求。用户可以应用任何R函数 - 在这种情况下,我们执行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
)

0
假设您的数据框是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()中的值来调整过去几个月的时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接