Part of the workflow for my project requires creating contours from a raster. I am able to generate the contours using raster::rasterToContour and can convert to a polygon using the sf package in R, but am having some trouble getting the desired outcome.
Here is a scaled-down example of what I am currently doing:
library(raster)
library(sf)
raster <- raster(matrix(c(rep(0,5),
0,1,1,1,0,
0,1,0,1,0,
0,1,1,1,0,
rep(0,5)), nrow = 5, ncol = 5))
plot(raster)
contour <- rasterToContour(raster, level = 0.5)
plot(contour, add = TRUE)
sf <- st_as_sf(contour) %>% st_polygonize()
plot(sf, col = "gray50", border = "black")
The initial contour plot seems to work appropriately for what I need. However, I can't seem to figure out how to avoid the central region becoming filled, as shown here. I would like the central portion to become a hole in the larger polygon so that it looks like this. I'm sure I can achieve this by pulling the polygons into GIS software, but it would be helpful to do so within R.
You could try
st_cast("POLYGON")instead ofst_polygonize():Or perhaps
starsandstars::st_contour():Created on 2024-02-09 with reprex v2.1.0