This is a script that takes selected fields (selected_fields) from a shape file and turns each into a raster. If the field is character-based categories, it ratifies the raster. At the end, you have a list of rasters. You can then bind these into a brick or perform other list-wise operations on them.
require(rgdal)
library(sf)
# The input file geodatabase
fgdb <- "land.gdb"
# Read the feature class
fc <- st_read(dsn=fgdb,layer="all_land")
forest <- read.csv("IDs_to_keep.csv")
world.map <- fc[fc$gridcode %in% forest$gridcode,]
library(raster)
ext <- extent(world.map)
gridsize <- 30
r <- raster(ext, res=gridsize)
selected_fields <- c("Own", "Cover", "Secondary")
library(fasterize)
test <- lapply(selected_fields, function(x) {
myraster <- fasterize(world.map, r, field=x)
names(myraster) <- x
if(is.factor(world.map[,x][[1]])) {
field <- x
myraster <- ratify(myraster)
rat <- levels(myraster)[[1]]
rat[[field]] <- levels(world.map[,x][[1]])[rat$ID]
levels(myraster) <- rat}
return(myraster)})