r - calculate average correlation for neighboring pixels through time -


i have stack of 4 rasters. average correlation through time between pixel , each of 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 pixel @ position x, has 8 neighbors @ ne, e, se, s etc positions, want 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 average value saved @ position x in resulting raster. edge cells na or, if possible flag calculate average correlation cells touches (either 3 or 5 cells). thanks!

i don't believe @pascal's suggestion of using focal() work because focal() takes single raster layer argument, not stack. solution easiest understand. made more efficient minimizing number of times extract values 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 each focal cell: <- adjacent(s, 1:ncell(s), directions=8, sorted=t)  ##  create column store correlations: out <- data.frame(a) out$cors <- na  ##  loop on focal cells , adjacencies, ##    extract values across layers , calculate ##    correlation, storing in appropriate row of ##    our output data.frame: (i in 1:nrow(a)) {     out$cors[i] <- cor(c(s[a[i,1]]), c(s[a[i,2]])) }  ##  take mean of correlations focal cell id: r_out_vals <- aggregate(out$cors, by=list(out$from), fun=mean)  ##  create new raster object store our mean correlations in ##    focal cell locations: r_out <- s[[1]] r_out[] <- r_out_vals$x  plot(r_out) 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -