Search code examples
rdataframespatialr-sfbounding-box

Get bounding box for coordinates in columns of dataframe


I have a dataframe with two columns of type numeric.

foo <- data.frame(replicate(2,sample(10.1:15.2,100,rep=TRUE)))

    X1 X2
1 13.1 15.1
2 13.1 11.1
3 13.1 15.1
4 10.1 13.1
5 15.1 11.1
6 13.1 11.1
...

These numbers represent coordinates in 4326. X1 is latitude, X2 is longitude. How would I get the bounding box for all these coordinates?


Solution

  • Convert to sf and use st_bbox:

    library(sf)
    
    foo %>% 
      st_as_sf(coords = c("X2","X1"), crs = 4326) %>% 
      st_bbox()
    
    # xmin ymin xmax ymax 
    # 10.1 10.1 15.1 15.1