r-spatial / spdep

Spatial Dependence: Weighting Schemes and Statistics
https://r-spatial.github.io/spdep/
116 stars 26 forks source link

plot.nb fails when the object coords mixes POLYGON and MULTIPOLYGON #144

Closed agila5 closed 3 months ago

agila5 commented 3 months ago

Dear @rsbivand, I just started reading Chapters 14 and 15 of https://r-spatial.org/book/, and I found the following (IMO slightly annoying) behaviour which is detailed in the next reprex.

library(spdep)
#> Loading required package: spData
#> Loading required package: sf
#> Linking to GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE
data(pol_pres15, package = "spDataLarge")
if (!all(st_is_valid(pol_pres15))) pol_pres15 <- st_make_valid(pol_pres15)
nb <- poly2nb(pol_pres15, queen = TRUE)

Then, I checked ?plot.nb and I noticed that the function requires a coords argument that can be specified as a sfc object (with point or polygons). However:

plot(nb, coords = st_geometry(pol_pres15))
#> Error in plot.nb(nb, coords = st_geometry(pol_pres15)): Point-conforming geometries required

whereas

plot(nb, coords = as(pol_pres15, "Spatial"))

After some simple debugging, I noticed that the problem occurs here https://github.com/r-spatial/spdep/blob/208f1b3bb27f52865afd0d11497dd179509b728f/R/plot.nb.R#L11-L14 since

st_geometry_type(pol_pres15) |> factor() |> table()
#> 
#>      POLYGON MULTIPOLYGON 
#>         2430           65

which implies that

inherits(st_geometry(pol_pres15), "sfc_POLYGON")
#> [1] FALSE
inherits(st_geometry(pol_pres15), "sfc_MULTIPOLYGON")
#> [1] FALSE

Created on 2024-03-20 with reprex v2.0.2

Do you think it might be reasonable to replace the previous test with something like?

if (all(st_geometry_type(coords) %in% c("POLYGON", "MULTIPOLYGON")) {
    coords <- st_point_on_surface(coords)
}
edzer commented 3 months ago

Or alternatively, all(st_dimension(coords) == 2)

rsbivand commented 3 months ago

https://github.com/r-spatial/spdep/commit/97ca382a40d6fb22186cb9fdfd14f26cbc1bf6ad seems to deal with this, using @edzer 's helpful suggestion. Also corrected in nb2lines. Please let me know if this resolves the problem for you, @agila5

agila5 commented 3 months ago

Works perfectly, thank you both!