Reputation: 387
Suppose yt is a time series. What I want is xt = max(yt,yt -1,...,yt - N). My code is
x<-unlist(lapply(seq_along(y),function(i)max(y[seq.int(max(1L,i-N),i)])))
This code uses lapply
and there are repetitive reads, so I think it isn't taking full advantage of SIMD features of the processor. Is there a faster solution?
Upvotes: 1
Views: 168
Reputation: 887203
We can use roll_max
from RcppRoll
library(RcppRoll)
roll_max(v1, n=3)
v1 <- 1:10
Upvotes: 1