This function work in two ways:
If
byLayer = TRUE(default), it will convert all non-NAcells in aGRasterto a single user-defined value, leavingNAcells asNA. Alternatively, it can convertNAcells to a user-defined value, and all non-NAcells toNA.Regardless, if the input is a "stack" ofGRasters, it will return a stack with the same number of raster layers.If
byLayer = FALSEandxis a "stack" ofGRasters,, it will return a singleGRasterlayer. This layer will have a user-defined value in all cells that had noNAs across all rasters, andNAs in cells where at least one raster had anNA. This is useful for masking out areas where data are missing in any of the rasters. Ifinvert = TRUE, it will return a singleGRasterlayer with a user-defined value in all cells that had at least oneNAacross all rasters, andNAs in cells where all rasters had non-NAvalues.
Usage
# S4 method for class 'GRaster'
maskNA(x, value = 1, invert = FALSE, retain = FALSE, byLayer = TRUE)Arguments
- x
A
GRaster.- value
Numeric: Value to which to assign to masked cells. The default is 1.
- invert
Logical: If
FALSE(default), convert non-NAcells tovalue, and leaveNAcells as-is. IfTRUE, convert allNAcells tovalue, and non-NAcells toNA.- retain
Logical: If
invertisTRUEandretainisFALSE(default), non-NAcells will retain their value. This argument is ignored ifinvertisFALSE. Ignored ifbyLayer = FALSE.- byLayer
Logical: If
TRUE(default), implement the masking layer-by-layer. Ifxis a stack of raster, it will return a stack with the same number of layers. IfFALSE, return a single raster layer withNAin all cells that had at least oneNAacross all layers, andvaluein all cells that had noNAs across all layers. Ifinvert = TRUE, it will return a single raster layer withvaluein all cells that had at least oneNAacross all layers, andNAin all cells that had noNAs across all layers.
Examples
if (grassStarted()) {
# Setup
library(terra)
### Mask layer-by-layer
# Elevation raster
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Convert non-NA to 1, NA cells remain NA
elevMask <- maskNA(elev)
elevMask
plot(c(elev, elevMask))
# Convert NA to 1, non-NA cells become NA
elevInvertMask <- maskNA(elev, invert = TRUE)
elevInvertMask
plot(c(elev, elevInvertMask))
# Convert NA to 200, non-NA cells keep their values
elevInvertRetain <- maskNA(elev, value = 200, invert = TRUE, retain = TRUE)
elevInvertRetain
plot(c(elev, elevInvertRetain))
### Mask *across* layers
# Load forest raster, which has many NAs
madForest2000 <- fastData("madForest2000")
forest2000 <- fast(madForest2000)
x <- c(elev, forest2000)
maskByLayer <- maskNA(x)
maskAcrossLayers <- maskNA(x, byLayer = FALSE)
maskByLayer
maskAcrossLayers
}
