Conversion from categorical SpatRast loses levels
ailich opened this issue · 1 comments
ailich commented
When converting a SpatRast that has factor levels to a raster object, the result is no longer a factor.
library(terra)
#> Warning: package 'terra' was built under R version 4.2.2
#> terra 1.7.12
library(raster)
#> Warning: package 'raster' was built under R version 4.2.2
#> Loading required package: sp
#> Warning: package 'sp' was built under R version 4.2.2
r<- rast(matrix(data=c(1,1,1,2,2,2,3,3,3), nrow=3))
levels(r)<- data.frame(ID=1:3, class= c("c1", "c2", "c3"))
is.factor(r)
#> [1] TRUE
levels(r)
#> [[1]]
#> ID class
#> 1 1 c1
#> 2 2 c2
#> 3 3 c3
raster(r) |> is.factor()
#> [1] FALSE
raster(r) |> levels()
#> NULL
Created on 2023-02-21 with reprex v2.0.2
rhijmans commented
Thanks, I now get:
library(terra)
library(raster)
r <- rast(matrix(data=c(1,1,1,2,2,2,3,3,3), nrow=3))
levels(r)<- data.frame(ID=1:3, class= c("c1", "c2", "c3"))
raster(r)
#class : RasterLayer
#dimensions : 3, 3, 9 (nrow, ncol, ncell)
#resolution : 1, 1 (x, y)
#extent : 0, 3, 0, 3 (xmin, xmax, ymin, ymax)
#crs : NA
#source : memory
#names : class
#values : 1, 3 (min, max)
#attributes :
# ID class
# 1 c1
# 2 c2
# 3 c3