11

I want to mask out a raster based on the values of a polygon: i.e., set to NA all values of the raster that are not covered by the polygons. However, it seems that raster::mask() masks out cells (i.e. set them to NA) even if they are partially covered?

This is similar to the question: Cropping a raster by a polygon - cells missing that are partially outside the polygon, but unlike crop(), mask() does not have the snap="out" option.

Check: here the right point of the triangle touches a cell, yet that cells is masked out.

library(raster)
library(sp)

r <- raster(xmn=1, xmx=5, ymn=1, ymx=5, nrows=4, ncols=4)
r[] <- 1:length(r)

Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(4.1,4,2),c(2,3,2)))

SpP = SpatialPolygons(list(Polygons(list(Sr1), "s1"), Polygons(list(Sr2), "s2")), 1:2)

plot(mask(r, SpP))
plot(SpP,  add=TRUE)

enter image description here

1 Answer 1

20

The documentation is indeed a little confusing. It states that:

[...] all cells that are not covered by the Spatial object are set to updatevalue

But actually, here covered means only if the cell's centroid is in the polygon. Indeed, mask() calls rasterize(), which states:

For polygons, values are transferred if the polygon covers the center of a raster cell.

The solution I found was to use rasterize() directly, with the getCover=TRUE option, which returns the coverage of each cell. Then set to NA values that have zero, and use that as the new mask:

SpP_ras <- rasterize(SpP, r, getCover=TRUE)
SpP_ras[SpP_ras==0] <- NA

plot(mask(r, SpP_ras))
plot(SpP,  add=TRUE)

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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