Last chance! 50% off unlimited learning
Sale ends in
A SpatRaster layer can be a categorical variable (factor). Like factor
s, 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 categories
you can set categories for any layer and you can also set the "active" category if there are multiple categories for a layer.
# S4 method for SpatRaster
is.factor(x)# S4 method for SpatRaster
levels(x)
# S4 method for SpatRaster
levels(x)<-value
# S4 method for SpatRaster
cats(x, layer, active=FALSE)
# S4 method for SpatRaster
categories(x, layer=1, value, index)
SpatRaster
positive integer, the layer number or name
logical. If TRUE
, only return the active category
a data.frame (ID, category) or vector with category names
positive integer, indicating the column in data.frame
value
to be used as the (active) category, (not counting the first column with the cell values)
list (levels, cats) or data.frame (cats for a single layer); logical (is.factor, setCats)
# NOT RUN {
set.seed(0)
r <- rast(nrows=10, ncols=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], value=10:12)
levels(x) <- d
x
## switch categories
cats(x, 1)
# get current index
activeCat(x)
# set index
activeCat(x) <- 3
plot(x, col=c("green", "blue", "light gray"))
text(x, digits=3, cex=.75, halo=TRUE)
r <- as.numeric(x)
r
activeCat(x) <- 2
p <- as.polygons(x)
plot(p, "letters", col=c("green", "blue", "light gray"))
# }
Run the code above in your browser using DataLab