Creating vector with minimum values of another vector

I have a problem that is very simple, but curiously it is taking me longer than I imagined. I'll put it generically here, and in the end I put an example. I hope to be clear:

I have a numeric vector X1, with N observations. I need to create another vector, X2, based based on minimum value of vector X1.

But the condition is a little strange: every observation of this vector X2 must be the minimum value of the last 126 observations of vector X1, in the same position.

In other words, each observation i of vector X2 is the result of the minimum between (i-125):i of vector X1.

I have tried in many ways, by for, creating functions and using apply, using index, but it did not work.

Consider the example:


and the warning msgs:

Warning messages:
1: In (i - 125):i :
  numerical expression has 375 elements: only the first used


for(j in 126:length(x1)){

In this case, only the last observation (500) which does not result in NA.

Welcome to the community!

I think the following does what you want.


x1 <- rnorm(500, 2, 3)

i <- 126:length(x = x1)

x2 <- sapply(X = i,
             FUN = function(t) {
               min(x1[(t - 125):t])

Another option using rolling functions from caTools

x1 <- rnorm(500,2,3)

x2 <- runmin(x1, 126, endrule = "trim")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.