2012-01-29 44 views
2

如果我有20個值的數據幀:滑動cummax R中

x <- data.frame(runif(20,10,90)) 

,我想創造無累計最大值比5個之前的值我會怎麼做,更多的另一列?基本上它會是先前5個值的滑動窗口。下面是一個正常的cummax如何完成的數據和滑動cummax,我指出了變化的明顯。從動物園

rollapplyr(x,5,max,partial = TRUE,by.column = FALSE) 

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 

回答

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 
+0

你可以用'x [1:4,2] < - cummax(x [1:4,1])替換那些' – GSee 2012-01-29 23:48:33

3

你也許可以做這樣的事情。 (我不經常使用這個包,所以我不知道爲什麼我需要指定by.column = FALSE以確保partial論證工作如我所料。也許別人可以對此有何評論...)

+0

它是一個錯誤。在遇到'max'時,它會嘗試使用'rollmax'來加速計算,但'rollmax'不支持'partial'。 ('rollmax'也不支持'by.column',但它通過添加'by.column'知道它不會使用'rollmax'。)這樣可以避免bug:'rollapplyr(x,5,( max),partial = TRUE)'。如果可以在開始處插入NA,並且速度更快,那麼這也適用:'rollmax(x,5,fill = NA,align =「right」)'。 – 2012-01-29 14:01:23