I have a raster where every cell is a 1. I also have a polygon of buffer areas that fall within the raster. I want to assign all raster cells that intersect the polygon geometrics to NA. But the two files have different extents and origins. I don't see a reason to share code, since I build the raster and polygons based on proprietary data. But I can illustrate it. The black grid represents my current raster, the blue cicle is the polygon:

Overlaid raster and grid

What function will allow me to reassign the raster value of all cells that intersect the polygon? The raster would become as follows:

enter image description here

  • Though you cannot provide the proprietary data, there is still reason to provide a minimal reproducible example. As things currently stand, your question cannot be answered properly because there are many different ways of storing rasters and polygons in R. I may have a way of doing it for certain data structures, but I'm unsure if it would be at all helpful for your case. Could you provide more information? – Austin Graves Nov 21 '20 at 18:49

You may as well use the function mask; according to the function help: "You can use inverse=TRUE to set the cells that are not NA (or other maskvalue) in the mask"

m = matrix(rep(1,100), ncol = 10)
r = raster(m)

point = st_sfc(st_point(c(.8,.1))) # let's create a point and buffer it to have a polygon
pol = st_buffer(point,.1)
plot(pol, add = T)
r_masked = mask(r, as(pol, "Spatial"), inverse = T )

par(mfrow = c(1,2))
plot(r, axes = F, legend =F, bty = "n")
plot(r_masked, axes = F, legend = F)
plot(pol, add = T)

enter image description here

  • I didn't realize there was an inverse=T option with mask! I'm excited to try this out! Thank you. – C. Ashley Nov 21 '20 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.