The use case - distances of centroids of multiple polygons from a common origin - is a frequent one. It does not even require sf::st_lenght()
, mere sf::st_distance()
is usually enough.
Consider this piece of code, built on top of the highly recommended {tigris}
package (the gold standard for US admin area data, because Topologically Integrated Geographic Encoding and Referencing system and the US Census Bureau).
Note that:
- the use of mutate creates a new variable within the existing
usa
dataframe (including all variables, such as the state abbreviation)
- the use of dot in
sf::st_centroid(.)
that tells dplyr to calculate the centroid for current row (and use it as first input of distance measurement; the second will be the KY centroid)
You will get the somewhat expected warning that st_centroid assumes attributes are constant over geometries
which should be OK
library(tigris)
library(dplyr)
library(sf)
usa <- states(resolution = "20m") %>%
select(STUSPS) # for sake of brevity...
kentucky_centroid <- usa %>%
filter(STUSPS == "KY") %>%
st_centroid()
usa %>%
mutate(distance_from_KY = st_distance(st_centroid(.), kentucky_centroid)) %>%
arrange(distance_from_KY)
# Simple feature collection with 56 features and 2 fields
# Geometry type: MULTIPOLYGON
# Dimension: XY
# Bounding box: xmin: -179.2311 ymin: -14.60181 xmax: 179.8597 ymax: 71.43979
# Geodetic CRS: NAD83
# First 10 features:
# STUSPS distance_from_KY geometry
# 1 KY 0.0 [m] MULTIPOLYGON (((-89.5712 36...
# 2 TN 208537.0 [m] MULTIPOLYGON (((-83.98762 3...
# 3 IN 277130.7 [m] MULTIPOLYGON (((-86.3296 38...
# 4 OH 389955.7 [m] MULTIPOLYGON (((-80.51915 4...
# 5 WV 427427.3 [m] MULTIPOLYGON (((-80.85847 3...
# 6 IL 438699.6 [m] MULTIPOLYGON (((-89.17208 3...
# 7 AL 550984.6 [m] MULTIPOLYGON (((-85.4883 30...
# 8 SC 571278.6 [m] MULTIPOLYGON (((-79.45002 3...
# 9 GA 571963.9 [m] MULTIPOLYGON (((-81.09538 3...
# 10 VA 584212.4 [m] MULTIPOLYGON (((-77.76715 3...