简体   繁体   English

如何正确对齐滚动平均值

[英]How to properly align a rolling mean

I am using rollmean 我正在使用rollmean

library(zoo)
library(TTR)
library(data.table)
date = seq(as.Date("2016-01-01"),as.Date("2016-01-10"),"day")
value =seq(1,10,1)
mydata = data.frame (date, value)
mydata
setDT(mydata)[, paste0('F1',2:3) := lapply(2:3, function(x) rollmean(value, x, fill = rep(NA,x-1),align="right") ),][]

         date value F12 F13
 1: 2016-01-01     1  NA  NA
 2: 2016-01-02     2 1.5  NA
 3: 2016-01-03     3 2.5   2
 4: 2016-01-04     4 3.5   3
 5: 2016-01-05     5 4.5   4
 6: 2016-01-06     6 5.5   5
 7: 2016-01-07     7 6.5   6
 8: 2016-01-08     8 7.5   7
 9: 2016-01-09     9 8.5   8
10: 2016-01-10    10 9.5   9

and I'd like the mean in a row to be calculated using the previous n observations. 我想用前面的n个观察值来计算连续的平均值。 You can see in the data above that the mean in the second row for F12 is 1.5 which is the mean of 2 & 1. I'd like that to be NA and the 1.5 to appear in row 3 so that the mean of F12 in the 3rd row would be 1.5. 你可以在上面的数据中看到,F12第二行的平均值是1.5,这是2和1的平均值。我希望它是NA,而1.5则出现在第3行,这样F12的平均值就是第3行是1.5。 Is that possible? 那可能吗? I tried changing the align parameter but no luck. 我尝试更改对齐参数,但没有运气。 Thank you. 谢谢。

We may need to wrap it with shift : 我们可能需要用shift包装它:

setDT(mydata)[, paste0('F1',2:3) := lapply(2:3, function(x) 
     shift(rollmean(value, x, fill = NA, align="right")) )]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM