2

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.

B. Davis
  • 3,391
  • 5
  • 42
  • 78
  • this is essentially a duplicate of http://stackoverflow.com/questions/32890375/focal-function-how-do-i-get-the-value-of-the-center-pixel-and-use-this-value-wi/32900327#32900327 – Robert Hijmans Dec 11 '15 at 21:46

1 Answers1

2

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.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
shekeine
  • 1,445
  • 10
  • 22
  • Thanks. After running the code, the mean values were incorrect. If 1/9 is the argument to `matrix`, then the `fun` needs to be `sum` This code works as well `focal(r, w=matrix(1,nrow=3,ncol=3), fun=mean)` as mentioned here http://rstudio-pubs-static.s3.amazonaws.com/1057_1f7e9ac569644689b7e4de78c1fece90.html – B. Davis Dec 11 '15 at 19:15
  • Yeah, that's correct, I did not think to check the code you posted originally too closely. See edit. – shekeine Dec 11 '15 at 19:49