Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

factors

Factors


Description

A SpatRaster layer can be a categorical variable (factor). Like factors, categories are stored as indices (integers) that have an associated label. For a SpatRaster, the index starts at 0, and cannot exceed 255.

The categories can be inspected with levels and cats. With levels<- you can set the categories of the first layer by providing a vector of labels (the first value will be for cells with value 0, the second for 1, etc). You can also provide a data.frame that must have two or more columns, the first one identifying the cell values and the other column(s) providing the category labels. To set categories for multiple layers you can provide levels<- with a list with one element for each layer.

With setCats you can set it for any layer and you can also set the variable of interest if there are multiple categories.

Usage

## S4 method for signature 'SpatRaster'
is.factor(x)

## S4 method for signature 'SpatRaster'
levels(x)

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

## S4 method for signature 'SpatRaster'
cats(x, layer)

## S4 method for signature 'SpatRaster'
setCats(x, layer=1, value, index)

Arguments

x

SpatRaster

layer

positive integer, the layer number or name

value

a data.frame (ID, category) or vector with category names

index

positive integer, indicating the column in value to be used as the category

Value

list (levels, cats) or data.frame (cats for a single layer); logical (is.factor, setCats)

Examples

set.seed(0)
r <- rast(nrow=10, ncol=10)
values(r) <- sample(3, ncell(r), replace=TRUE)
is.factor(r)

cls <- c("forest", "water", "urban")
# make the raster start at zero
x <- r - 1
levels(x) <- cls
names(x) <- "land cover"
is.factor(x)
x

plot(x, col=c("green", "blue", "light gray"))
text(x, digits=3, cex=.75, halo=TRUE)

# raster starts at 3
x <- r + 2
is.factor(x)

# approach 1
levels(x) <- c("", "", "", "forest", "water", "urban")

# approach 2, also showing the use of two categories
d <- data.frame(id=3:5, cover=cls, letters=letters[1:3])
levels(x) <- d
x

## switch categories
head(cats(x, 1))
# get current index
setCats(x, 1)
# set index 
setCats(x, 1, index=3)
setCats(x, 1)
plot(x, col=c("green", "blue", "light gray"))
text(x, digits=3, cex=.75, halo=TRUE)

#setCats(x, 1, index=2)
#p <- as.polygons(x)
#plot(p, "cover", col=c("green", "blue", "light gray"))

terra

Spatial Data Analysis

v1.2-10
GPL (>= 3)
Authors
Robert J. Hijmans [cre, aut] (<https://orcid.org/0000-0001-5872-2872>), Roger Bivand [ctb] (<https://orcid.org/0000-0003-2392-6140>), Karl Forner [ctb], Jeroen Ooms [ctb] (<https://orcid.org/0000-0002-4035-0289>), Edzer Pebesma [ctb] (<https://orcid.org/0000-0001-8049-7069>)
Initial release
2021-05-12

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.