Skip to content
Prev 140477 / 398506 Next

Loop problem

Jamie Ledingham wrote:
Hi again Jamie,
I had a bit of time tonight and recognized your problem. I think the 
following function will do what you want, although it is probably not 
the most elegant solution. I would check it manually with a small data 
file and a small "howmany" argument to make sure that it is picking up 
the maxima you want.

find.max.rain<-function(raindata,howmany) {
  # a lazy way of getting the same structure as raindata
  # it assumes that raindata has the data structure that you want
  maxrain<-raindata[1:howmany,]
  for(i in 1:howmany) {
   # get the current number of rows
   nrows<-dim(raindata)[1]
   # find the first maximum value
   thismax<-which.max(raindata$cumrain)
   # transfer it to the return data frame
   maxrain[i,]<-raindata[thismax,]
   # calculate the minimum index for the 48 hour gap
   mindex<-thismax-48
   # make sure it is at least 1
   if(mindex < 1) mindex <- 1
   # calculate the maximum index for the gap
   maxdex<-thismax+48
   # make sure it doesn't go past the end of the data frame
   if(maxdex > nrows) maxdex<-nrows
   # chop out that time period
   raindata<-raindata[-(mindex:maxdex),]
  }
  return(maxrain)
}

Jim