title: R focal (raster)- conditional filter (only run if window center is value 1)
body: <p>I'd like to filter a large raster, but only run the filter if the center cell of the window is a specific value.  Essentially I'd like to remove some speckle (false positives) from an image (pixels of 0 or 1), but only run the filter if window center is 1. </p>
  
  <pre><code># create some raster data
  library(raster)
  r &lt;- raster(ncols=12, nrows=12)
  set.seed(0)
  r[] &lt;- round(runif(ncell(r))*0.7 )
  plot(r)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/dSYBP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dSYBP.jpg" alt="enter image description here"></a></p>
  
  <pre><code># custom filter
  w=matrix(1,5,5)
  gameOfLife &lt;- function(x) {
  f &lt;- focal(x, w=w, pad=TRUE, padValue=0)
  #  window with with less than 5 cells die
  x[f &lt; 5] &lt;- 0
  # window with 5 or more cells live
  x[f &gt;= 5] &lt;- 1
  x
  }
  
  plot(gameOfLife(r))
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/QX5Iw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QX5Iw.jpg" alt="enter image description here"></a></p>
  
  <p>The 2 circled cells, above, meet the criteria (having at least 5 values of 1 around them) but were initially a 0 and I want them to remain a 0. Thus, the filter only applies if the center value is already a 1.</p>
  
  <p>Hope that makes sense.
  Many thanks in advance</p>