r-spatial / sf

Simple Features for R
https://r-spatial.github.io/sf/
Other
1.3k stars 288 forks source link

st_within() does not work as expected after sf object has st_union operation #1844

Closed jakemanger closed 1 year ago

jakemanger commented 2 years ago

Describe the bug After you run a st_union operation on an sf multipolygon, running st_within(another_polygon, unionised_polygon) with this unionised_polygon results in mostly empty matches.

To Reproduce

The below script creates a reproducible example of this behaviour:

library(sf)
library(dplyr)

# read in original polygon
nc <- st_read(system.file("shape/nc.shp", package="sf"))

# create a grouping variable
nc$group <- rep(1:4, each=25)

# create a new grouped sf object using st_union()
nc_grouped <-
  nc %>%
  group_by(group) %>%
  summarise(geometry=st_union(geometry))

plot(nc %>% st_geometry())
plot(nc_grouped %>% st_geometry())

# see what polygons are within the groupings
within_matches <- nc %>%
  st_geometry() %>%
  st_within(nc_grouped)

print(within_matches)

The original polygon is: image And the second polygon to check if the first is within it is: image

In this case, I will get the following matches as an output:

Sparse geometry binary predicate list of length 100, where the predicate was `within'
first 10 elements:
 1: (empty)
 2: 1
 3: 1
 4: (empty)
 5: (empty)
 6: (empty)
 7: (empty)
 8: (empty)
 9: 1
 10: 1

However, because these are the exact same geometries, they should all match, not be empty.

R version 4.1.0 (2021-05-18) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 18363) Matrix products: default locale: [1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 [3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C [5] LC_TIME=English_Australia.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] dplyr_1.0.7 sf_1.0-2 loaded via a namespace (and not attached): [1] Rcpp_1.0.7 rstudioapi_0.13 magrittr_2.0.1 units_0.7-2 tidyselect_1.1.1 [6] R6_2.5.1 rlang_0.4.11 fansi_0.5.0 s2_1.0.7 wk_0.5.0 [11] tools_4.1.0 grid_4.1.0 KernSmooth_2.23-20 utf8_1.2.2 cli_3.1.0 [16] e1071_1.7-9 DBI_1.1.1 ellipsis_0.3.2 class_7.3-19 tibble_3.1.4 [21] lifecycle_1.0.1 crayon_1.4.1 purrr_0.3.4 vctrs_0.3.8 glue_1.4.2 [26] proxy_0.4-26 compiler_4.1.0 pillar_1.6.3 generics_0.1.0 classInt_0.4-3 [31] pkgconfig_2.0.3 GEOS GDAL proj.4 GDAL_with_GEOS USE_PROJ_H PROJ "3.9.1" "3.2.1" "7.2.1" "true" "true" "7.2.1"
Nowosad commented 2 years ago

Just to add a tiny info to this issue -> this problem does not exist with sf_use_s2(FALSE).