# 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:

``````set.seed(1)
x1<-rnorm(500,2,3)
i<-seq(126,length(x1))
x2<-min(x1[(i-125):i])
``````

and the warning msgs:

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

or

``````for(j in 126:length(x1)){
x2<-rep(NA,length(x1))
x2[j]<-(min(x1[j-125:j]))
}
``````

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.

``````set.seed(1)

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`

``````set.seed(1)
x1 <- rnorm(500,2,3)

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

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