2
votes

I am trying to calculate the difference between a raster cell and the mean value in a 3 x 3 neighborhood.

With this raster

r = raster(ncol=10, nrow=10, xmn=0, xmx=100, ymn=0, ymx=100)
set.seed(123)
values(r) = round(runif(ncell(r),1,100))

I could use something similar to

r2 <- focal(r2, w=matrix(1,nrow=3,ncol=3), fun=)

but think I need a custom function as the argument to fun to calculate the mean value of the 3 x 3 neighborhood and then subtract the value from the center cell.

I know I could do this with two different raster layers but suspect there is an better way as outlined above.

Any suggestions would be greatly appreciated.

1
this is essentially a duplicate of stackoverflow.com/questions/32890375/…Robert Hijmans

1 Answers

2
votes

You could do it in two steps:

#First, get the mean in a 3x3 neighbourhood
r2 <- focal(r, w=matrix(1,nrow=3,ncol=3), fun=mean)

#Then subtract the focal mean from the original cell values using simple raster arithmetic:
r3 <- r - r2

You can then easily wrap the above steps in a function it that's more convenient, cheers.