问题
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}
回答1:
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
回答2:
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 :-(
来源:https://stackoverflow.com/questions/32890375/focal-function-how-do-i-get-the-value-of-the-center-pixel-and-use-this-value-wi