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)

Arguments

ras

Raster* object.

mask

Raster* object or POLYGON/MULTIPOLYGON sf::sf() object.

inverse

Logical. If TRUE, areas in mask that are not NA are masked

updatevalue

Convert all masked cells in ras to this value (default is NA)

Value

Raster* object

See also

Examples

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
system.time(ras.masked <- fast_mask(ras, msk))
#> user system elapsed #> 0.02 0.00 0.02
plot(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
system.time(ras.masked <- raster::mask(ras, msk.sf))
#> user system elapsed #> 14.01 0.03 14.29
system.time(ras.masked <- fast_mask(ras, msk.sf))
#> although coordinates are longitude/latitude, st_intersection assumes that they are planar
#> user system elapsed #> 0.70 0.00 0.72