Question: why does levels() return a list object?
atsyplenkov opened this issue · comments
Anatolii Tsyplenkov commented
Hey, guys
I am just curious, why does levels()
return a list object? Is there any practical reason for this, or is it just a legacy from the {raster}
package?
library(terra)
#> terra 1.7.71
set.seed(0)
r <- rast(nrows = 10, ncols = 10)
values(r) <- sample(3, ncell(r), replace = TRUE)
cls <- data.frame(id = 1:3, cover = c("forest", "water", "urban"))
levels(r) <- cls
class(levels(r))
#> [1] "list"
Created on 2024-05-09 with reprex v2.1.0
Jason Flower commented
I'd say this is because if you have a multi-layer raster, the levels for each raster are separate elements in the list:
library(terra)
#> terra 1.7.71
set.seed(0)
r <- rast(nrows = 10, ncols = 10)
values(r) <- sample(3, ncell(r), replace = TRUE)
cls <- data.frame(id = 1:3, cover = c("forest", "water", "urban"))
levels(r) <- cls
class(levels(r))
#> [1] "list"
#multi-layer raster
r2 <- c(r,r)
levels(r2)
#> [[1]]
#> id cover
#> 1 1 forest
#> 2 2 water
#> 3 3 urban
#>
#> [[2]]
#> id cover
#> 1 1 forest
#> 2 2 water
#> 3 3 urban
Created on 2024-05-09 with reprex v2.1.0