0

I want to mask a raster by a polygon, the R script was as followed. However, some cells with only partially covered weren't included in the masked raster as listed in the picture link (https://drive.google.com/open?id=1EVehD8lYsR4oTr0SJPlhZhtti9b4WXxG), is there any method to accomplish?

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)

0

This is already answered in this question:

R raster: masking a raster by polygon also remove cells partially covered?

The solution described by Matifou is to rasterize() the polygon first:

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

plot(mask(r, SpP_ras))
plot(SpP,  add=TRUE)
  • Is there any way to calculate the fraction of these partially covered cells? – ivor Jul 22 at 13:13
  • @Ivor ask this as a new question? – Spacedman Jul 22 at 14:23

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