Search code examples
rloopsfor-loopbinning

loop latitude binning in R


I am a novice at using R and am having some trouble creating a loop.

I have a dataframe of hourly data spanning from 2017-2019, and these have latitude and longitude coordinates in degrees, alongside other columns. The latitude is in both negative a positive values spanning across hemispheres - from -90 to +90. I want to create a loop that separates these by 5 degree latitude bands (e.g. -45 to -40) and then outputs these in individual tables.

I am currently using the following code to divide up the original dataframe hourly.avg.bylat into individual dataframes i.e. lat.bin.neg90_neg85, which I would go on to write as tables, however I feel this is rather clunky and time consuming and would prefer to use a loop to do this.

lat.bin.neg90_neg85<-as.data.frame(split.data.frame(hourly.avg.bylat, cut(hourly.avg.bylat$lat, c(-90, -85), include.lowest=TRUE, labels = "")))

I understand I could use for(i in seq(-90, 90, 5)) but am a bit lost as to how to string it all together.


Solution

  • You can use a list to store the output and do the computation in a loop:

    output=list()
    for(i in seq(-90, 85, 5))
    {
      output[[paste0(i,"_",i+5)]]<-as.data.frame(split.data.frame(hourly.avg.bylat,
                                   cut(hourly.avg.bylat$lat, c(i, i+5),
                                   include.lowest=TRUE, labels = "")))
    }
    

    Then you can access each bins with e.g. output[["-90_-85"]]

    paste0(i,"_",i+5) creates the string for the list key. Note that the loop stops at 85, because we cut between i and i+5, so we don't want to go between 90 and 95. Since you did not provide the raw data I can't test it, let me know if there is an issue.

    EDIT

    As suggested by DaveT, it can be done in a single line using:

    split(hourly.avg.bylat, cut((hourly.avg.bylat$lat, breaks=seq(-90, 90, 5)))