0

Example with a 3*3 neighborhood where the sum is multiplied with the center value "center".

library(raster)
r <- raster(ncol=10, nrow=10)
r[] <- 1:100
f<-function(x,center) {sum(x)*center}
r.f <- focal(r, w=matrix(1,3,3),fun=f}
burbot
  • 175
  • 1
  • 5

2 Answers2

2

Carl's approach will work. It might be more efficient to do:

library(raster)
r <- raster(ncol=10, nrow=10)
r[] <- 1:100
r.f <- focal(r, w=matrix(1,3,3)) * r
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
1

Interesting. Since the argument fun must accept multiple values, it may well be the case that you should use

f <-function(x) {
y = sum(x)/x[5]
return(y)
}

Because you're always feeding an x which is a 3x3 matrix, so the fifth element will be the center one. No R on the machine I'm using to type this, so I can't verify :-(

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73