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?
2 Answers
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 sf
and terra
:
library(sf)
library(terra)
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)
now rasterize:
tsh = rasterize(as(sh,"SpatVector"), y,field="Coverage")
and plot:
plot(tsh)
Note this is still a raster of numbers, so if you try writing it to some file format you might lose the labels.
Here is Spacedman's solution using a more direct path
library(terra)
sh = vect("./kasanka habitats.shp")
y = rast(sh, 200, 200)
tsh = rasterize(sh, y, field="Coverage")