Is that what you want? library(raster) # your reproducible! raster r <- raster() r[] <- sample(0:2,ncell(r),replace=TRUE)
funX <- function(x){sum(x==1)} res1 <- focal(r,fun=funX,w=matrix(1, ncol=3, nrow=3)) # or in this special case (sum if 1) also rn <- r==1 res2 <- focal(rn,w=matrix(1, ncol=3, nrow=3)) # more general (eg sum if 2): funX <- function(x){sum(x[x==2])} res3 <- focal(r,fun=funX,w=matrix(1, ncol=3, nrow=3)) Matteo >>> anusheema <anushe...@gmail.com> 05/18/14 8:57 PM >>> Hi! 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) -- View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Focal-function-in-R-tp7586466.html Sent from the R-sig-geo mailing list archive at Nabble.com. _______________________________________________ R-sig-Geo mailing list R-sig-Geo@r-project.org https://stat.ethz.ch/mailman/listinfo/r-sig-geo _______________________________________________ R-sig-Geo mailing list R-sig-Geo@r-project.org https://stat.ethz.ch/mailman/listinfo/r-sig-geo