calculate average correlation for neighboring pixels through time

1k views Asked by At

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!

1

There are 1 answers

3
Forrest R. Stevens On BEST ANSWER

I don't believe @Pascal's suggestion of using focal() could work because focal() 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:

library(raster)  

set.seed(2002)
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)

##  Calculate adjacent raster cells for each focal cell:
a <- adjacent(s, 1:ncell(s), directions=8, sorted=T)

##  Create column to store correlations:
out <- data.frame(a)
out$cors <- NA

##  Loop over all focal cells and their adjacencies,
##    extract the values across all layers and calculate
##    the correlation, storing it in the appropriate row of
##    our output data.frame:
for (i in 1:nrow(a)) {
    out$cors[i] <- cor(c(s[a[i,1]]), c(s[a[i,2]]))
}

##  Take the mean of the correlations by focal cell ID:
r_out_vals <- aggregate(out$cors, by=list(out$from), FUN=mean)

##  Create a new raster object to store our mean correlations in
##    the focal cell locations:
r_out <- s[[1]]
r_out[] <- r_out_vals$x

plot(r_out)