3

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)

1 Answer 1

7

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)
3
  • How can I save the final raster in discrete 0 and 1 values? The following line creates a continuous raster from 0 to 1: writeRaster(final, filename, datatype="INT1U") How can I fix it? @Robert Hijmans
    – Sarash
    Commented Aug 17, 2022 at 10:53
  • You can supply the filename argument to app, but if the results are not as you expect, then please ask a new question that includes example data (generated by code) that reproduces the problem. Commented Aug 17, 2022 at 15:04
  • What if rc1, rc2 and rc3 have characters instead of numbers?
    – jmutua
    Commented Mar 28 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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