raster icon indicating copy to clipboard operation
raster copied to clipboard

Cannot write multiband raster with factor levels to tif

Open ailich opened this issue 3 years ago • 0 comments

I've tried with both the CRAN (3.5.15) and development versions (3.5.19) but I can't seem to write a multiband raster object that contains a categorical layer.

library(raster)

r<- raster(nrow=100, ncol=100)
set.seed(5)
values(r[[1]])<- rnorm(n = ncell(r), mean = 20, sd = 3)
r<- stack(r,r) #add second layer
set.seed(5)
values(r[[2]])<- sample(1:7, size = ncell(r), replace = TRUE)

r[[2]]<- as.factor(r[[2]])
levels(r[[2]])[[1]]<- data.frame(ID=1:7, features = c("c1","c2", "c3", "c4", "c5", "c6", "c7"))
levels(r[[2]])
# [[1]]
# ID features
# 1  1       c1
# 2  2       c2
# 3  3       c3
# 4  4       c4
# 5  5       c5
# 6  6       c6
# 7  7       c7

writeRaster(r, "rtest.tif", overwrite=TRUE)
# Error in .checkLevels(levs[[j]], value[[j]]) : 
#   new raster attributes (factor values) should be in a data.frame (inside a list)

writeRaster(r[[2]], "rtest2.tif", overwrite=TRUE) #Works if you only write a single band

ailich avatar Jun 05 '22 21:06 ailich