Search code examples
rraster

Overlaying a conditional function over a raster brick to produce a single layer in R


I'm trying to produce a binary raster layer based on a single conditional function applied over many layers. Here's an example I found of what I want to accomplish, however, this example is only for 3 layers. If I want to check for conditions over 25 layers, is there a way to do this that doesn't require 25 arguments input into the function?

library(raster)
set.seed(0)
r <- raster(ncol=10, nrow=10, xmn=0, xmx=10, ymn=0, ymx=10)
r1 <- setValues(r, round(runif(ncell(r), 1, 2)))
r2 <- setValues(r, round(runif(ncell(r), 1, 2)))
r3 <- setValues(r, round(runif(ncell(r), 1, 2)))
s <- stack(r1, r2, r3)


res1 <- overlay(s, fun =   
    function(x,y,z) { 
    ifelse( x == 2 | y == 2 | z ==2, 1, 0) 
              })

Solution

  • You can do:

    r <- any(s == 2)
    

    or

    z <- calc(s, function(x) any(x==2))