Create a vector footprint of a multi-part raster [R]

223 Views Asked by At

I've read a raster into my R session, using this code:

raster <- stack("raster.tif")

and now I'd like to make a simple feature (sf) object representing the outline of that raster. I can't use a bounding box because the raster is multi-part so the bounding box would be much larger than the raster. So the footprint also needs to be a multi-part feature (sf multipolygon).

I'd appreciate any help with this. Thanks!

Mark

1

There are 1 best solutions below

0
at80 On

If you want each raster in the stack you need to loop over each one with lapply. This will return a list of polygon layers. You then need to convert each component of the list to an sf multipolygon. Lastly, you need to concatenate the features (note that c is the c() function). shp should be your multipolygon. You may not want to dissolve the polygons, you didn't really make it clear what you wanted.

a <- lapply(as.list(raster), rasterToPolygons, dissolve=TRUE)
b <- lapply(a, st_as_sf) # convert to sf multipolygon
shp <- Reduce(c, b) # combine all polygons to one

As a side note, it's probably not great to use raster as a variable name because the raster package has a function called raster.