This is a fast implementation of raster::mask()
. It masks values in a Raster object according to values in another Raster or polygon layer. Note that this function might sometimes be slower than raster::mask()
when the mask is a Raster. Largest speed gains occur for polygon masks.
fast_mask(ras = NULL, mask = NULL, inverse = FALSE, updatevalue = NA)
ras | Raster* object. |
---|---|
mask | Raster* object or POLYGON/MULTIPOLYGON |
inverse | Logical. If TRUE, areas in |
updatevalue | Convert all masked cells in |
Raster* object
library(raster) size <- 100 ras <- raster(ncol = size, nrow = size, vals = rep(1, size*size)) msk <- raster(ncol = size, nrow = size, vals = runif(size*size)) msk[msk < 0.5] <- NA # Using raster as mask system.time(ras.masked <- raster::mask(ras, msk))#> user system elapsed #> 0.01 0.00 0.02#> user system elapsed #> 0.02 0.00 0.02plot(ras)plot(msk)plot(ras.masked)# Using polygon layer as mask msk.sp <- as(msk, 'SpatialPolygonsDataFrame') msk.sf <- sf::st_as_sf(msk.sp) system.time(ras.masked <- raster::mask(ras, msk.sp))#> user system elapsed #> 12.90 0.06 13.21#> user system elapsed #> 14.01 0.03 14.29#>#> user system elapsed #> 0.70 0.00 0.72