R – Reclassify Rasters Using Terra Package

rrasterreclassifyterra

I have several rasters with values from 0 to 7, and I want to reclassify pixels using 3 different areas and different conditions.

I want to reclass

rc1 pixel value of (1 or 3 or 5 or 7) to 1

rc2 pixel value of (2 or 3 or 6 or 7) reclassify to 1

rc3 pixel value of (4 or 5 or 6 or 7) reclassify to 1 and

then combine the three raster objects to the final raster with only values of 0, 1 or NA.

border1 <- terra:vect("")
border2 <- terra:vect("")
border3 <- terra:vect("")
r <- terra::rast("filename.tif") 

rc1 <- terra::mask(r, border1)
rr1 <- terra::classify(rc1, ?????)

rc2 <- terra::mask(r, border2)
rr2 <- terra::classify(rc2, ?????)
    
rc3 <- terra::mask(r, border3)
rr3 <- terra::classify(rc3, ?????)
    
final <- terra::app(c(rr1, rr2, rr2), max, na.rm = TRUE)

Best Answer

Example data

library(terra)
r <- rast(ncol=18, nrow=9)
values(r) <- sample(7, ncell(r), replace=TRUE)
r[,5:8] <- NA    
rc1 <- rc2 <- rc3 <- r
rc1[1:6,] <- NA
rc2[3:9,] <- NA
rc3[c(1:3,6:9),] <- NA

Solution

m1 <- cbind(c(1,3,5,7), 1)
m2 <- cbind(c(2,3,6,7), 1)
m3 <- cbind(c(4,5,6,7), 1)

rr1 <- classify(rc1, m1, others=0)
rr2 <- classify(rc2, m2, others=0)
rr3 <- classify(rc3, m3, others=0)

x <- app(c(rr1, rr2, rr3), max, na.rm=T)
Related Question