Learn R Programming

terra (version 1.1-4)

factors: Factors

Description

These functions allow for defining a SpatRaster layer as a categorical variable (factor). These can be inspected and set with levels and cats. These methods are the same except that with levels<- you can only set the categories of the first layer. Like factors in R, categories are stored as indices (integers) that have an associated label. In a SpatRaster, the index starts at 0, and cannot be larger than 255. as.factor makes the first layer of a SpatRaster a categorical variable. You can then use levels<- to replace the lables.

The "Raster Attribute Table" (RAT) is similar in concept. A main difference with categries is that there can be many labels (variables) assocuated with one index. The RAT is a data.frame; the first column ("ID") has the unique cell values of the layer.

Usage

# S4 method for SpatRaster
is.factor(x)

# S4 method for SpatRaster as.factor(x)

# S4 method for SpatRaster levels(x)

# S4 method for SpatRaster levels(x)<-value

# S4 method for SpatRaster cats(x)

# S4 method for SpatRaster cats(x, layer=1)<-value

# S4 method for SpatRaster rats(x)

# S4 method for SpatRaster rats(x, layer=1)<-value

Arguments

x

SpatRaster

layer

positive integer, the layer number or name

value

With cats<- and levels<- this can be a character vectors with new labels or a two column data.frame. The first column is an integer cell value, and the second column is the character label. With rats<- this is a data.frame. The first column is an integer cell value, and any number and type of additional columns is allowed

Value

SpatRaster; list (e.g., levels); boolean (is.factor)

Examples

Run this code
# NOT RUN {
set.seed(0)
r <- rast(nrow=10, ncol=10)
values(r) <- sample(3, ncell(r), replace=TRUE) + 2
is.factor(r)

cls <- c("forest", "water", "urban")
levels(r) <- cls
names(r) <- "land cover"
is.factor(r)
r

f <- as.factor(r)
# }

Run the code above in your browser using DataLab