title: Focal function in R
body: <p>I want to run focal values for neighbourhood of focal cells using a matrix, with a function preferably. My data has 0, 1, and 2 as values, and I want to add values of "1" only, if I am using the focal function.</p>
  
  <p>It's probably a very simple question, and I have tried many combinations, but still not getting the desired results.</p>
  
  <p>Please help!</p>
  
  <p>Here's one of the codes that I was attempting:</p>
  
  <pre><code># to generate the function
  
    my.function &lt;- function (x) {
      ux &lt;- unique(x)
      ux [if (x==1) ux &lt;- focal(in_image, w=matrix(1/9, ncol=3, nrow=3)), fun=sum]
      }
  
  # to run the focal window for the desired function
  
    r_new &lt;- focal(in_image, w=matrix(1/9, ncol=3, nrow=3), fun=my.function)
  </code></pre>