'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 1:[1]
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
Solution 2:[2]
Slightly more succint using sfheaders if you want a light-weight option for using in a package.
sfheaders::sf_bbox(foo, x = "X2", y = "X1")
# xmin ymin xmax ymax
# 10.1 10.1 15.1 15.1
# attr(,"class")
# [1] "bbox"
But if you're using sf in your workflow anyway, then the pure sf approach is fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maël |
| Solution 2 |
