Kelvin
Kelvin

Reputation: 23

Min function keeps returning wrong value in loop inR

I am trying to run a loop that returns and stores the minimum value in a sequence. The code however keeps returning the last indexed value of the loop. Here's my function

low<- seq(1,100)
five.D_MIN <- c(rep(0, length=length(low)))
for (j in 1:length(five.D_MIN)-4){
  five.D_MIN[j] <- min(low[j:j+4])
}

Upvotes: 1

Views: 76

Answers (3)

GKi
GKi

Reputation: 39667

As other have stated already, you have to put brackets like j:(j+4). And to make it more stable for length lower than 4 try:

low <- seq(1,100)
five.D_MIN <- integer(max(0, length(low) - 4))
for(j in head(seq_along(low), -4)) {
#for(j in seq_len(max(0, length(low) - 4))) { #Alternative
  five.D_MIN[j] <- min(low[j:(j+4)])
}

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101568

You missed () to surround j+4. The difference can be seen from the following example

> 1:1 + 4
[1] 5

> 1:(1 + 4)
[1] 1 2 3 4 5

Upvotes: 1

Basti
Basti

Reputation: 1763

You have to put additional brackets because your selection is wrong :

low<- seq(1,100)
five.D_MIN <- c(rep(0, length=length(low)))
for (j in 1:(length(five.D_MIN)-4)){
  five.D_MIN[j] <- min(low[j:(j+4)])
}

Upvotes: 3

Related Questions