ecohealthalliance / fasterize

High performance raster conversion for modern spatial data 🚀🌏▦
https://ecohealthalliance.github.io/fasterize/
Other
182 stars 15 forks source link

Allow geometry collections if they contain only polygon and multipolygons? #25

Closed gergness closed 1 year ago

gergness commented 6 years ago

When I read in some shape files, my sf object has geometry type "geometrycollection" because it contains both polygons and multipolygons. If I try to use fasterize on an object like this, I get an error saying that my geometry must be a polygon or multipolygon. I suppose I could convert polygons to multipolygons, but was hoping fasterize could be less strict about checking geometry type.

library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3
library(fasterize)
#> 
#> Attaching package: 'fasterize'
#> The following object is masked from 'package:graphics':
#> 
#>     plot

poly1 <- list(matrix(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1), ncol = 2))
poly2 <- list(matrix(c(3, 3, 4, 4, 3, 3, 4, 4, 3, 3), ncol = 2))

x <- data.frame(
  x = 1:2
)

x$geometry <- st_sfc(
    list(
      st_polygon(poly1),
      st_multipolygon(list(poly1, poly2))
    )
)

x <- st_sf(x)

fasterize(x, raster(x))
#> Error in fasterize(x, raster(x)): sf geometry must be POLYGON or MULTIPOLYGON
ateucher commented 6 years ago

You can use sf::st_collection_extract() to get a (MULTI)POLYGON object:

fasterize(st_collection_extract(x, "POLYGON"), raster(x))
mdsumner commented 1 year ago

and see #1, personally I think it's right to use sf to set up the inputs (other streaming and efficiency options that aren't provided by sf can be relevant here)