bubble
bubble

Reputation: 23

Creating vector with minimum values of another vector [R]

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.

Upvotes: 2

Views: 221

Answers (1)

IRTFM
IRTFM

Reputation: 263481

The for loop should have had the same parentheses you had in the attempt that prompted the warnings (and should NOT have initialized the vector inside the for-loop, since that erased the prior values.):

x2<-rep(NA,length(x1))
for(j in 126:length(x1)){

  x2[j]<-(min(x1[(j-125):j]))
}

Upvotes: 1

Related Questions