burbot
burbot

Reputation: 195

Focal function: How do I get the value of the center pixel and use this value within the focal fun argument?

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}

Upvotes: 0

Views: 924

Answers (2)

Robert Hijmans
Robert Hijmans

Reputation: 47091

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

Upvotes: 2

Carl Witthoft
Carl Witthoft

Reputation: 21502

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 :-(

Upvotes: 1

Related Questions