1

I want to rasterize a SpatialPolygonsDataFrame and keep the values of a factor column.

Consider the following code (from Processing vector to raster faster with R):

library('raster')
library('rgdal')
# Load a SpatialPolygonsDataFrame example (Brazil administrative level 2) shapefile
dat <- raster::getData(country = "BRA", level = 2)

# Convert NAMES to factor 
dat$NAME_1 <- as.factor(dat$NAME_1)

# Define RasterLayer object
r.raster <- raster()

# Define raster extent
extent(r.raster) <- extent(dat)

# Define pixel size
res(r.raster) <- 0.1

# rasterize
ras <- rasterize(x = dat, y = r.raster, field = "NAME_1")

To access the values from column NAME_1 I tried:

ras_factor <- ratify(ras)
levels(ras_factor)

There are no factor values.

Where do I find the original values from column NAME_1? How can I rasterize a SpatialPolygonsDataFrame and transfer the factor values to the resulting ras object?

1

ratify is the right option, but you should do an extra step. You need to create a dictionary to store desired values and create a numeric column to be used in rasterize process:

library('raster')
library('rgdal')
# Load a SpatialPolygonsDataFrame example (Brazil administrative level 2) shapefile
dat <- raster::getData(country = "BRA", level = 2)

# get names
nam <- unique(dat$NAME_1)

# create a data.frame
nam_df <- data.frame(ID = 1:length(nam), nam = nam)

# Place IDs
dat$ID <- nam_df$ID[match(dat$NAME_1,nam_df$nam)]

# Define RasterLayer object
r.raster <- raster()

# Define raster extent
extent(r.raster) <- extent(dat)

# Define pixel size
res(r.raster) <- 0.1

# rasterize
ras <- rasterize(x = dat, y = r.raster, field = "ID")

# ratify raster
r <- ratify(ras)

# Create levels
rat <- levels(r)[[1]]
rat$names <- nam_df$nam
rat$IDs <- nam_df$ID
levels(r) <- rat

rasterVis::levelplot(r)

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.