Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Robinlovelace opened this issue Dec 15, 2022 · 0 comments

Comments

@Robinlovelace
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant