I have a stack of 4 rasters. I would like the average correlation through time between a pixel and each of its 8 neighbors.
some data:
library(raster)
r1=raster(matrix(runif(25),nrow=5))
r2=raster(matrix(runif(25),nrow=5))
r3=raster(matrix(runif(25),nrow=5))
r4=raster(matrix(runif(25),nrow=5))
s=stack(r1,r2,r3,r4)
so for a pixel at position x, which has 8 neighbors at the NE, E, SE, S etc positions, I want the average of
cor(x,NE)
cor(x,E)
cor(x,SE)
cor(x,S)
cor(x,SW)
cor(x,W)
cor(x,NW)
cor(x,N)
and the average value saved at position x in the resulting raster. The edge cells would be NA or, if possible a flag to calculate the average correlation just with the cells it touches (either 3 or 5 cells). Thanks!
I don't believe @Pascal's suggestion of using
focal()
could work becausefocal()
takes a single raster layer as an argument, not a stack. This is the solution that is easiest to understand. It could be made more efficient by minimizing the number of times you extract values for each focal cell: