如何计算R中的7天移动平均线? [英] How to calculate 7-day moving average in R?
本文介绍了如何计算R中的7天移动平均线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 zoo
包的 rollmean
函数来计算一个简单的 7 天移动平均线.该函数有一个参数 align
,如果我输入right"、center"或left",它会更改值.它们有什么区别?
I'm using the rollmean
function of zoo
package to calculate a simple 7-day moving average. The function has an argument align
and if I put "right", "center" or "left" it changes the values. What's the difference between them?
示例代码:
test <- sample(1:50)
data <- rollmean(test, 7, fill = list(NA, NULL, NA), align = "right")
test <- cbind(test, data)
推荐答案
我认为将所有 3 个结果并排查看很有启发性:
I think it is instructive to see the results of all 3 next to each other:
library(zoo)
means <- sapply(c("right","center","left"),
function(x)zoo::rollmean(test,7,align = x, na.pad = TRUE))
cbind(test,means)
test right center left
[1,] 6 NA NA 19.28571
[2,] 50 NA NA 21.42857
[3,] 11 NA NA 15.28571
[4,] 16 NA 19.28571 15.00000
[5,] 1 NA 21.42857 19.42857
[6,] 26 NA 15.28571 25.28571
[7,] 25 19.28571 15.00000 22.71429
[8,] 21 21.42857 19.42857 24.42857
[9,] 7 15.28571 25.28571 22.00000
[10,] 9 15.00000 22.71429 23.42857
...
[40,] 41 27.28571 31.85714 33.57143
[41,] 49 29.42857 31.71429 33.85714
[42,] 35 33.71429 31.42857 30.00000
[43,] 20 31.85714 33.57143 26.85714
[44,] 44 31.71429 33.85714 25.42857
[45,] 28 31.42857 30.00000 NA
[46,] 18 33.57143 26.85714 NA
[47,] 43 33.85714 25.42857 NA
[48,] 22 30.00000 NA NA
[49,] 13 26.85714 NA NA
[50,] 10 25.42857 NA NA
这篇关于如何计算R中的7天移动平均线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文