我有以下数据集:
date <- StockData[1:10,2]
x <- c(2,4,2,3,5,1,6,2,3,4)
df <- as.data.frame(cbind(x,date))
df
x date
1 2 2019-06-28
2 4 2019-07-01
3 2 2019-07-02
4 3 2019-07-03
5 5 2019-07-04
6 1 2019-07-05
7 6 2019-07-08
8 2 2019-07-09
9 3 2019-07-10
10 4 2019-07-11
现在,我想创建一个新列,其滚动平均值要提前5(n)天,因此数据集如下所示:
x date five.day.average
1 2 2019-06-28 3.2
2 4 2019-07-01 3
3 2 2019-07-02 3.4
4 3 2019-07-03 3.4
5 5 2019-07-04 3.4
6 1 2019-07-05 3.2
7 6 2019-07-08 NA
8 2 2019-07-09 NA
9 3 2019-07-10 NA
10 4 2019-07-11 NA
换句话说,我想要一个公式/函数,其功能与程序包rollmean
中的zoo
相同,但是要使时间倒退,而不要倒退(因为k
rollmean
不能为负。
提前谢谢!
答案 0 :(得分:3)
一个选项是frollmean
中的data.table
library(data.table)
setDT(df)[, five.day.average := frollmean(x, 5, align = 'left')]
df
# x date five.day.average
# 1: 2 2019-06-28 3.2
# 2: 4 2019-07-01 3.0
# 3: 2 2019-07-02 3.4
# 4: 3 2019-07-03 3.4
# 5: 5 2019-07-04 3.4
# 6: 1 2019-07-05 3.2
# 7: 6 2019-07-08 NA
# 8: 2 2019-07-09 NA
# 9: 3 2019-07-10 NA
#10: 4 2019-07-11 NA
或者使用rollmean
中的zoo
rollmean(df$x, 5, align = 'left', fill = NA)
#[1] 3.2 3.0 3.4 3.4 3.4 3.2 NA NA NA NA
df <- structure(list(x = c(2L, 4L, 2L, 3L, 5L, 1L, 6L, 2L, 3L, 4L),
date = c("2019-06-28", "2019-07-01", "2019-07-02", "2019-07-03",
"2019-07-04", "2019-07-05", "2019-07-08", "2019-07-09", "2019-07-10",
"2019-07-11")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))
答案 1 :(得分:3)
在 base 中,您可以使用filter
来获得滚动平均值。要使其向前看 rev
。
rev(filter(rev(df$x), rep(1/5, 5), sides=1))
# [1] 3.2 3.0 3.4 3.4 3.4 3.2 NA NA NA NA