ropensci / stplanr

Sustainable transport planning with R
https://docs.ropensci.org/stplanr
Other
417 stars 66 forks source link

Add subsetting function that returns objects whose centroids are within the subsetting object 'y' #511

Open Robinlovelace opened 1 year ago

Robinlovelace commented 1 year ago

Reproducible example below, developed with @eugenividal. I've needed this many times, perhaps a dozen times per year, would be good to have a function in a package that does it.

Return features the centroids of which are inside another object

sf::st_within
#> function (x, y, sparse = TRUE, prepared = TRUE, ...) 
#> st_geos_binop("within", x, y, sparse = sparse, prepared = prepared, 
#>     ...)
#> <bytecode: 0x5556ef75b298>
#> <environment: namespace:sf>
polygons = spData::lnd
polygons_central = polygons[polygons$NAME == "City of London", ]
study_region = polygons[polygons_central, ]
study_region = sf::st_union(study_region)
subset_touching = polygons[study_region, ]
plot(polygons$geometry)
plot(subset_touching, col = "grey", add = TRUE)
#> Warning in plot.sf(subset_touching, col = "grey", add = TRUE): ignoring all but
#> the first attribute
plot(study_region, col = "red", add = TRUE)

# Function to return only polygons whose centroids are inside
x = polygons
y = study_region
filter_polygon_centroids = function(x, y) {
  x_centroids = sf::st_centroid(x)
  x_in_y = sf::st_intersects(x_centroids, y)
  x_in_y_logical = lengths(x_in_y) > 0
  x[x_in_y_logical, ]
}

subset_test = filter_polygon_centroids(x = polygons, y = study_region)
#> Warning in st_centroid.sf(x): st_centroid assumes attributes are constant over
#> geometries of x
plot(subset_test, col = "green", add = TRUE)
#> Warning in plot.sf(subset_test, col = "green", add = TRUE): ignoring all but the
#> first attribute


# Test output of st_intersects..

Created on 2022-12-15 with reprex v2.0.2