Search code examples
rpolygoncropmaskraster

R crop raster using polygon keeping cells along the border


I'm trying to crop this raster over Italy but the output seems to miss some of the cells along the border. See areas highlighted in red in the picture below: enter image description here

How can I keep all the cells that cross the borders?

Below is my script:

library(raster)

# Load data
x <- raster("x.nc")
IT <- getData(name = "GADM", country = "Italy", level = 0)

# Mask and crop
x_masked <- mask(x, IT)
x_masked_cropped <- crop(x_masked, IT)

# Plot
plot(x_masked_cropped)
plot(IT, add = T)

Solution

  • You could identify all raster cells intersecting Italy and set the remaining, i.e. non-intersecting pixels to NA. Make sure to retrieve cells with their respective weights via cellFromPolygon(..., weights = TRUE) - otherwise, only cells that have their center inside Italy will be returned (see also ?raster::extract).

    ## identify cells covering italy and set all remaining pixels to NA
    cls <- cellFromPolygon(x, IT, weights = TRUE)[[1]][, "cell"]
    x[][-cls] <- NA
    
    plot(trim(x))
    plot(IT, add = TRUE)
    

    enter image description here