mardi 26 janvier 2016

Checking For Largest Value in a Matrix Using "For" and "If" Loop

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!

Aucun commentaire:

Enregistrer un commentaire