Calculate the average correlation for adjacent pixels in time

I have a stack of 4 rasters. I need an average correlation between the 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 positions NE, E, SE, S, etc., I want the average value

 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 stored at position x in the resulting raster. Loud cells will be NA or, if possible, a flag to calculate the average correlation only with the cells to which it touches (or 3 or 5 cells). Thanks!

+6
source share
1 answer

I donโ€™t think the @Pascal suggestion for using focal() might work, because focal() uses a single raster layer as an argument, not a stack. This is the solution that is easiest to understand. This can be made more efficient by minimizing the number of times you retrieve the 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) 
+5
source

Source: https://habr.com/ru/post/989372/


All Articles