elflyao
elflyao

Reputation: 387

How to get the maximum value of N past observations

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

Answers (1)

akrun
akrun

Reputation: 887203

We can use roll_max from RcppRoll

library(RcppRoll)
roll_max(v1, n=3)

data

v1 <- 1:10

Upvotes: 1

Related Questions