title: Overlay rasters in r to meet three different conditions using ifelse
body: <p>I'm trying to run an overlay function with rasters where I want to meet all of 3 different conditions at each cell (using <code>==</code> and <code>&gt;</code> or <code>&lt;</code> operators) and produce a single raster as output.</p>
  
  <p>Running <code>ifelse</code> with the <code>&amp;</code> operator seems to look at the conditions in a linear fashion from left to right - If the first two conditions are met then it will produce the if condition as output, regardless of the third condition. <code>&amp;&amp;</code> can't be used here because the result is not vectorized.</p>
  
  <p>You can see this with this example below where with the resulting raster it's clear that it is not evaluating all three arguments. First clue is that it produces results even if some values are NA in the third raster.</p>
  
  <p>I think I can get the result I want by first checking the condition of x and y and then with this result separately checking the condition of z with a different function, but I was hoping to be able to do it all in one function (seems like this should be possible, at least).</p>
  
  <p>Hoping someone can point me in the right direction.</p>
  
  <pre><code>library(raster)
  fn &lt;- system.file("external/test.grd", package="raster")
    s &lt;- stack(fn, fn,fn)
    #Create grids
    s[[1]] &lt;- round(runif(ncell(s), 1, 2))
    s[[2]] &lt;- round(runif(ncell(s), 1, 2))
    s[[3]] &lt;- round(runif(ncell(s), 1, 2))
    #convert some values in s[[3]] to NA
    s[[3]][s[[3]] == 1]&lt;- NA
  
    #run overlay function
    result.rast &lt;- overlay(s[[1]], s[[2]], s[[3]], fun =   
    function(x,y,z) { 
          ifelse( x == 2 &amp; y == 1 &amp; z ==2, 1, 0) 
    } )
  </code></pre>