raster icon indicating copy to clipboard operation
raster copied to clipboard

Incorrectly reading in factor levels

Open ailich opened this issue 3 years ago • 0 comments

It seems that levels of categorical rasters get a bit messed up when read in with raster::raster (or raster::brick when using multiband objects) . I've tried with the CRAN (3.5.15) and the development versions (3.5.19) of raster. Also, side note, writing to a ".grd" file does not save that the raster is a factor at all, but maybe this is a limitation of the file type.

library(raster)
library(terra)

r<- rast(nrow=100, ncol=100)
set.seed(5)
values(r)<- sample(1:7, size = ncell(r), replace = TRUE)

r<- as.factor(r)
levels(r)<- data.frame(ID=1:7, features = c("c1","c2", "c3", "c4", "c5", "c6", "c7"))

writeRaster(r, "rtest2.tif", overwrite=TRUE)
writeRaster(r, "rtest2.grd", overwrite=TRUE)

raster::raster("rtest2.tif") # Wrong factor levels from raster
# attributes :
#   ID category
# from:   0         
# to : 255 

terra::rast("rtest2.tif") # Correct factor levels from terra
# name        : features 
# min value   :       c1 
# max value   :       c7

is.factor(terra::rast("rtest2.grd"))  # Factor not preserved
# [1] FALSE

ailich avatar Jun 06 '22 17:06 ailich