I have a SpatialPolygonDataFrame which I need to convert to raster in R while keeping the categorical values of the polygon. I have tried various approaches but I have always either lost the values or converted them to numerical, which is not what I want. Can anyone help?
Factors are stored as numbers, so a raster of categorical values is just a raster of numbers with a lookup-table for the labels (which is the same as a standard vector of factors in R).
To do what you want using modern R spatial classes, use
Read the shape:
sh = st_read("./kasanka habitats.shp")
The "Coverage" variable (which I think is what you want to rasterize) is character at this point so we convert it to factor:
sh$Coverage = as.factor(sh$Coverage)
create a basis for rasterizing based on the extent of the shape:
y = rast(ext(sh),200,200)
tsh = rasterize(as(sh,"SpatVector"), y,field="Coverage")
Note this is still a raster of numbers, so if you try writing it to some file format you might lose the labels.