Friday, 30 August 2019

Reclassifying raster stack based on condition and other layers using R?


I want to reclassify raster r1 in the following form:




  • all the values that are larger than r2 to be 1

  • all the values that are less than r3 to be 0

  • all the rest of the values to be equal to r4


I use overlay to set the values for the first two conditions, but I can't do that for the third one. I am also interested to know how to put all these in one function.


library(raster)
r1 <- raster(nrow=5, ncol=5)
r1 <- setValues(r1, runif(ncell(r1)))
r2 <- setValues(r1, runif(25 ,0.6,0.9))

r3 <- setValues(r1, runif(25 ,0.2,0.4))
r4 <- setValues(r1, runif(25 ,1,2))


x <- overlay(r1, r2, fun=function(x,y){ x[x>y] <- 1; x})
x2 <- overlay(x, r3, fun=function(x,y){ x[x

Answer



To put this into a vectorized function you can use ifelse. If you stack your rasters then you do not need to piecemeal the reclassification and can apply a function to the stack.


Prepare data


library(raster)

r1 <- raster(nrow=5, ncol=5)
r <- stack(setValues(r1, runif(ncell(r1))),
setValues(r1, runif(25 ,0.6,0.9)),
setValues(r1, runif(25 ,0.2,0.4)),
setValues(r1, runif(25 ,1,2)))

Write reclassification function


rc <- function(x1,x2,x3,x4) {
ifelse( x1 > x2, 1, ifelse( x1 < x3, 0, x4) )
}


Apply function to raster stack


r.class <- overlay(r, fun=rc)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...