1
votes

I am trying to figure out the best way to calculate the maximum lat and long range (i.e. max "height" and "length") of a polygon.

Starting with an sf object of polygons, a possible approach would be:

  1. st_cast("POINT")
  2. extract lat and long for all points
  3. find the points with maximum lat, max long, min lat and min long per polygon
  4. calculate distances

However, I have to do this for hundreds of polygons and was wondering if there is a more elegant/easy way of doing it. I just cannot find anything on this (which seems strange)...

Thanks.

EDIT

Sure, I did not include an example because I think it is a very general question. But this could be of use:

library(sf)
library(dplyr)

demo(nc, ask = FALSE, verbose = FALSE)

Then what I need is to calculate the "length" (i.e. distance between max lon and min lon) and "height" (distance between max lat and min lat) for each of the polygons.

I think bbox() could help indeed. I think I could use a for loop or apply to run bbox() over each of the polygons. But then I have no idea how to convert the bbox() object into a data frame, to work from there. Any suggestions?

1
Hi! I think that you can probably use st_bbox to get an approximate value of max/min of lat/long. Can you share some sort of reproducible example?agila
Hi @agila I've added a simple example, but not sure if helpful. Thanks!birdMig
Hi again, just found this (github.com/r-spatial/sf/issues/1179) on 'bbox()', which my help - if I find a way through I'll post it.birdMig
sfheaders::sf_boxes( nc ) will give you the bounding box of each polygon if that helps?SymbolixAU

1 Answers

2
votes

I think you could apply something as the following example:

# packages
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1

# data
nc = st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source `C:\Users\Utente\Documents\R\win-library\3.6\sf\shape\nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> geographic CRS: NAD27
par(mar = rep(0, 4))
plot(st_geometry(nc))


# estimate bbox values for each feature: 
res <- as.data.frame(do.call("rbind", lapply(st_geometry(nc), st_bbox)))
head(res)
#>        xmin     ymin      xmax     ymax
#> 1 -81.74107 36.23436 -81.23989 36.58965
#> 2 -81.34754 36.36536 -80.90344 36.57286
#> 3 -80.96577 36.23388 -80.43531 36.56521
#> 4 -76.33025 36.07282 -75.77316 36.55716
#> 5 -77.90121 36.16277 -77.07531 36.55629
#> 6 -77.21767 36.23024 -76.70750 36.55629

Created on 2020-06-23 by the reprex package (v0.3.0)

The bboxes are not precisely equal to min/max of lat/long but maybe they are a good approximation.