R中周期变化的移动平均线 [英] Moving average with changing period in R

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

问题描述

我有一个名为abc的数据框,正在使用rollapply进行移动平均.以下代码有效:

I have a data frame named abc on which I'm doing moving average using rollapply. The following code works:

forecast <- rollapply(abc, width=12, FUN=mean, align = "right", fill=NA)

现在,我想做同样的事情,宽度是可变的,即第一个月为空,第二个月为空,第一个月的值就会到来.第三个月为(第一个月+第二个月/2),即第i个月,如果i<=12,则值为(sum(1:i-1)/(i-1)),而对于i>=12,则为最后一个月的平均值由forecast完成的12个月.请帮忙.

Now, I want to do the same thing with the width being variable, i.e. for the 1st month, it'll be empty, for the second month, first month's value will come. For the third month, it'll be (first month+second month/2), i.e. for the ith month, if i<=12, the value will be (sum(1:i-1)/(i-1)) and for i>=12 it will be the average of the last 12 months as done by the forecast. Please help.

推荐答案

以下是一些解决方法:

1)partial = TRUE

n <- length(x)
c(NA, rollapplyr(x, 12, mean, partial = TRUE)[-n])

注意rollapplyr末尾的r.

2)作为列表的宽度 rollapplywidth自变量可以是一个列表,以使ith列表元素是用于ith滚动计算的偏移量的向量.如果我们指定partial = TRUE,那么将忽略向量结尾处的偏移量.如果我们仅在列表中指定一个元素,它将被回收:

2) width as list The width argument of rollapply can be a list such that the ith list element is a vector of the offsets to use for the ith rolling computation. If we specify partial=TRUE then offsets that run off the end of the vector will be ignored. If we only specify one element in the list it will be recycled:

rollapply(x, list(-seq(12)), mean, partial = TRUE, fill = NA)

2a)而不是回收,而是根据partial可以将其写出.在这里,我们要width <- list(numeric(0), -1, -(1:2), -(1:3), ..., -(1:12), ..., -(1:12))可以这样计算:

2a) Rather than recycling and depending on partial we can write it out. Here we want width <- list(numeric(0), -1, -(1:2), -(1:3), ..., -(1:12), ..., -(1:12)) which can be calculated like this:

width <- lapply(seq_along(x), function(x) -seq_len(min(12, x-1)))
rollapply(x, width, mean)

如果您希望稍微修改一下规范,因为它非常灵活,那么这将是您的主要兴趣所在.

This one would mainly be of interest if you want to modify the specification slightly because it is very flexible.

注意::发帖者后来在评论中要求使用相同的滚动平均值,但不要滞后.就是这样:

Note: Later in the comments the poster asked for the same rolling average except for it not to be lagged. That would be just:

rollapplyr(x, 12, mean, partial = TRUE)

注意rollapplyr末尾的r.

更新一些改进和其他解决方案.

Update Some improvements and additional solutions.

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

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