如果我的数据框有20个值:
x <- data.frame(runif(20,10,90))
我想创建另一列累积最大值不超过之前的5个值,我该怎么做?基本上它将是前5个值的滑动窗口。下面是关于如何进行正常cummax和滑动cummax的数据,我指出了变化明显的位置。
runif normal cummax sliding cummax
1 42.84205 42.84205 42.84205
2 17.17040 42.84205 42.84205
3 50.08326 50.08326 50.08326
4 21.47712 50.08326 50.08326
5 59.30754 59.30754 59.30754
6 16.49770 59.30754 59.30754
7 89.52601 89.52601 89.52601
8 49.91727 89.52601 89.52601
9 69.84386 89.52601 89.52601
10 13.92894 89.52601 89.52601
11 56.39335 89.52601 89.52601
**12 28.30264 89.52601 69.84386**
13 60.09056 89.52601 69.84386
14 17.79935 89.52601 60.09056
15 63.53476 89.52601 63.53476
16 62.98458 89.52601 63.53476
17 67.21095 89.52601 67.21095
18 16.01599 89.52601 67.21095
19 39.99181 89.52601 67.21095
20 40.96641 89.52601 67.21095
答案 0 :(得分:3)
你可能会这样做:
rollapplyr(x,5,max,partial = TRUE,by.column = FALSE)
来自 zoo 包的。 (我不定期使用这个包,所以我不确定为什么我需要指定by.column = FALSE
以确保partial
参数按预期工作。也许其他人可以对此发表评论。 。)
答案 1 :(得分:2)
> library(TTR)
> set.seed <- 1234
> x <- data.frame(runif(20,10,90))
> x[[2]] <- runMax(x, n=5)
> x
runif.20..10..90. V2
1 79.18671 NA
2 13.34858 NA
3 35.37457 NA
4 11.10000 NA
5 29.12206 79.18671
6 66.51957 66.51957
7 34.64758 66.51957
8 50.68381 66.51957
9 14.13173 66.51957
10 55.16559 66.51957
11 19.71841 55.16559
12 81.42691 81.42691
13 11.17018 81.42691
14 72.64969 81.42691
15 17.19691 81.42691
16 51.53520 81.42691
17 40.74134 72.64969
18 15.60420 72.64969
19 35.65155 51.53520
20 63.47963 63.47963