title: Raster: Calculation on RasterStack only if not NA in other RasterLayer
body: <p>I have a <code>RasterStack</code> <code>s1</code> consisting of 400 layers with data from an island. The extent of the raster is cropped to the extent of the island, but due to its irregular shape, only around 20% of the pixels are actually land area and have data values; the other 80% are water and <code>NA</code>. </p>
  
  <p>I also have a land-water-mask <code>lwm</code> (<code>RasterLayer</code>), where land is coded as 1 and water as <code>NA</code>.</p>
  
  <p>I would like to do different kinds of cell-based calculations on <code>s1</code>, but noticed that these take a long time to finish. To speed things up, the calculations should only be carried out for cells that are land area, whereas water areas should always be <code>NA</code>. In pseudo-code:</p>
  
  <pre><code>for each cell:
      if cell is land
          do calculation
      if cell is water
          return(NA)
  </code></pre>
  
  <p>An requirement is <code>memory-safety</code>. </p>
  
  <p>Here is some sample data to illustrate the problem:</p>
  
  <pre><code>library(raster)
  # generate data
  lwm &lt;- raster(nrow = 5, ncol = 5)
  lwm[] &lt;- c(rep(NA, 10), rep(1, 5), rep(NA, 10))
  
  r1 &lt;- raster(nrow = 5, ncol = 5)
  r1[] &lt;- runif(ncell(r1)) * 10
  r2 &lt;- raster(nrow = 5, ncol = 5)
  r2[] &lt;- runif(ncell(r2)) * 10
  s1 &lt;- stack(r1, r2)
  s1 &lt;- mask(s1, lwm)
  
  # this works, but all NA-values on water are also unnecessarily evaluated 
  calc(s1, function(x) {sum(!is.na(x))})
  </code></pre>