rterra

How to change levels of multiple rasters in r?


I want to change the levels of raster stack. I am using the following code

library(terra)

set.seed(0)
r1 <- rast(nrows=10, ncols=10)
values(r1) <- sample(3, ncell(r1), replace=TRUE)
is.factor(r1)

r2 <- r1 

r <- c(r1, r2)

cls <- data.frame(id=1:3, cover=c("forest", "water", "urban"))
levels(r) <- cls

plot(r)

enter image description here

But it changes the levels of first layer only. How can I apply the levels for all the layers of a raster stack using terra R package?


Solution

  • In that case, you need a list of categories (one list element for each layer). For example:

    levels(r) <- lapply(1:nlyr(r), \(i) cls)
    # or 
    levels(r) <- replicate(nlyr(r), cls, simplify=FALSE)
    
    
    r
    #class       : SpatRaster 
    #dimensions  : 10, 10, 2  (nrow, ncol, nlyr)
    #resolution  : 36, 18  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
    #source(s)   : memory
    #names       :  cover,  cover 
    #min values  : forest, forest 
    #max values  :  urban,  urban