Search code examples
rroundinglatitude-longitude

How to round to specific decimal numbers in R


I currently have 2 data sets for global data. One is climate space and the other is species occurrence data. Both data sets have Latitude and Longitude columns. However, climate space Latitude and Longitude are listed as values NNN.75 or NNN.25. My occurrence data Latitude and Longitude are more specific and varies from NNN.01 to NNN.99. How do I round my occurrence data, using R, to the nearest .25 or .75 point?

Below is how I have rounded my occurrence points to 2 decimal places, but in order for me to join the data sets, I need the Latitude and Longitude values to match.

occurrence <- Solanum_OccurrenceClean %>% 
  mutate_at(vars(lat,lon),funs(round(.,digits=2)))

Thank you for the help!


Solution

  • In R there are two usefull operator for this %% and %/% which can be used to get the integer part and the decimal part of a divition. If you have this, and you divide by 1 yo can do it easy.

    set.seed(123)
    
    x <- rnorm(10, mean = 300) 
    
    ifelse(x %% 1 > 0.5,
           x %/%1 + 0.75,
           x %/%1 + 0.25)
    
    

    the vector went from this

    [1] 299.4395 299.7698 301.5587 300.0705 300.1293 301.7151 300.4609 298.7349 299.3131 299.5543
    

    to this

     [1] 299.25 299.75 301.75 300.25 300.25 301.75 300.25 298.75 299.25 299.75