Rasters in R – Create Presence/Absence (0/1) Rasters for Values in Categorical Raster in R

binarylogistic regressionrrasterreclassify

I am conducting a logistic regression analysis of spatial data for a project using STAN MCMC within R. The regression analysis itself is done, but now I need a way to apply the parameter estimates for different variables to raster data to generate prediction maps. Applying parameter estimates to continuous rasters in an ArcGIS Raster Calculator operation is straightforward (e.g., Intercept + 0.44*elevation – 0.23*dist_to_water…), but incorporating categorical rasters is more difficult. STAN requires categorical variables to be split up into a series of dummy variables, so my categorical rasters (e.g., native veg, surface geology, erosion class) need to be split up into a series of presence/absence (0/1) rasters for each value. For example, Native Vegetation has four categories, so I need four different 0/1 rasters that correspond to the distribution of each vegetation type. This is a similar problem to that discussed here.

However, I have six categorical rasters that each include a large number of values. As such, I would like to avoid having to manually create 0/1 rasters for each value using tools in ArcGIS like Extract by Attributes, Reclassify, or Conditional statements (e.g., Con(native_veg, 1, 0, "VALUE = 1")).

Is there a function in R that can iterate through unique raster values and create new 0/1 rasters for each?

Best Answer

The raster package has a function to do this for you in one line. Use layerize():

library(raster)
# make an example raster
r <- raster(nrow=100, ncol=100)
r[] <- round(runif(ncell(r),1,4),0)

# create presence/absence rasters, stored in a RasterBrick. 
r_dummy <- layerize(r)
plot(r_dummy[[1]])

Raster for "1" values

Related Question