[R] Loop problem

Jim Lemon jim at bitwrit.com.au
Thu Mar 27 12:03:46 CET 2008


Oops, missed the first line of the example:

storm.data<-data.frame(meas.index=10001:20000,cumrain=runif(10000,-10,10)+10)

You can generalize the function to whatever column names you have like this:

find.max.rain<-function(raindata,howmany,raincol) {
  # 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) {
   raindim<-dim(raindata)
   thismax<-which.max(raindata[[raincol]])
   cat(thismax," ")
   maxrain[i,]<-raindata[thismax,]
   mindex<-thismax-48
   if(mindex < 1) mindex <- 1
   maxdex<-thismax+48
   cat(mindex,maxdex," ")
   if(maxdex > raindim[1]) maxdex<-raindim[1]
   raindata<-raindata[-(mindex:maxdex),]
   cat(raindim[1],"  ")
  }
  cat("\n")
  return(maxrain)
}

find.max.rain(storm.data,50,"cumrain")

Jim



More information about the R-help mailing list