R 中前三个值的移动平均值 [英] Moving average of previous three values in R

查看:84
本文介绍了R 中前三个值的移动平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在zoo 包中有一个名为rollmean 的函数,它使您能够制作移动平均线.rollmean(x,3) 将采用下表中的上一个、当前和下一个值(即 4、6 和 2).这显示在第二列中.

In the zoo package there is a function called rollmean, which enables you to make moving averages. The rollmean(x,3) will take the previous, current and next value (ie 4, 6 and 2) in the table below. This is shown in the second column.

x   rollmean    ma3
4       
6   4.0 
2   4.3 
5   3.0         4.0
2   6.3         4.3
12  6.0         3.0
4   6.0         6.3
2               6.0

我想完成相同的工作,但要对第四行中的前 3 个值求平均值.这显示在第三列中.任何人都可以告诉我有助于实现此目的的函数的名称吗?

I would like to get the same job done, but by averaging out the previous 3 values in the fourth row. This is displayed in the third column. Can anybody tell me the name of the function that will help to accomplish this?

推荐答案

我努力寻找一个简单的移动平均线函数,它具有一定的灵活性来满足我的需求.我终于写了几个函数,扩展了基于 rinni 在上面评论中给出的过滤器函数的函数(但它本身不起作用,因为它将包括 3 周期平均值中的当前观察).

I struggled searching for a simple function for moving averages that had some flexibility to do what I needed. I finally wrote a couple functions extending the one based on the filter function which rinni gives above in the comment (but which itself won't work because it will include the current observation in the 3 period average).

  1. 包括当前观测值的移动平均函数

  1. Moving average function that includes the current observation

mav <- function(x,n){filter(x,rep(1/n,n), sides=1)} 

  • 不包含当前观测值的移动平均函数

  • Moving average function that does not include the current observation

    mavback <- function(x,n){
      a<-mav(x,1)
      b<-mav(x,(n+1))
      c<-(1/n)*((n+1)*b - a)
      return(c)
    }
    

  • 后视移动平均函数,不包括当前 obs,基于 [h1] 周期开始后的 [h2] 读数

  • Backward looking moving average function, not including current obs, based on [h2] readings starting [h1] periods back

    mavback1<-function(x,h1,h2){
      a<-mavback(x,h1)
      b<-mavback(x,h1-h2)
      c<-(1/h2)*(h1*a -(h1-h2)*b)
      return(c)
    }
    

  • 这篇关于R 中前三个值的移动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆