1

I'm having trouble with a for loop in a simple piece of code in R...

So I have a data frame with a bunch of precipitation data, with a bunch of "stations" (1-75) in rows and across in columns is values per month. I created a vector (which I called "Jan")of precipitation values for just the Jan column, so it looks something like this (I've put in random values for the purpose of this post) :

    V1
1   10
2   5
3   15
...
75  5

I want to use a "for" loop with "if" to return the highest value of this vector. However, the code I have below seems to just go through each value in the vector and always just returns the last value of then entire thing (i.e. in row 75, would return "5"). I know it's something in my "if" loop that isn't letting me actually text the values of the vector, rather it's testing the "row number" value. Any advice??

highest_ppt<- function(v) {
  i=0
 output<-v[i] #c(0,length(v))
  for (i in 2:length(v)){
    if (v[i] > (v[i-1])){
      output <- (v[i])
    }
  }
  return(output)
}

max_ppt <- highest_ppt(Jan)
max_ppt

Thank you!

1
  • 2
    I don't understand what you are trying to achieve. Isn't which.max function enough?
    – user3710546
    Jan 27, 2016 at 6:12

1 Answer 1

1

A for loop is the wrong approach here, but if you insist:

Max <- -Inf
for (i in seq_along(v)){
  if (v[i] > Max)
    Max <- v[i]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.