Anusheema
Anusheema

Reputation: 11

Focal function in R

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.

It's probably a very simple question, and I have tried many combinations, but still not getting the desired results.

Please help!

Here's one of the codes that I was attempting:

# to generate the function

  my.function <- function (x) {
    ux <- unique(x)
    ux [if (x==1) ux <- focal(in_image, w=matrix(1/9, ncol=3, nrow=3)), fun=sum]
    }

# to run the focal window for the desired function

  r_new <- focal(in_image, w=matrix(1/9, ncol=3, nrow=3), fun=my.function)

Upvotes: 0

Views: 3114

Answers (1)

Jeffrey Evans
Jeffrey Evans

Reputation: 2397

You are calling focal in your function. The function is passed to focal and should represent what you want done in the local window. I have no idea what the application of unique() is accomplishing. In your case and conditional sum would simply be:

r_new <- focal(in_image, w=matrix(1/9, ncol=3, nrow=3), fun=function(x) sum(x[x==1]))

Upvotes: 2

Related Questions