通过时间计算相邻像素的平均相关性

时间:2015-06-19 02:43:11

标签: r raster

我有一堆4个栅格。我希望像素与其8个邻居之间的平均时间相关性。

一些数据:

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)

所以对于位置x的像素,在NE,E,SE,S等位置有8个邻居,我想要平均值

cor(x,NE)
cor(x,E)
cor(x,SE)
cor(x,S)
cor(x,SW)
cor(x,W)
cor(x,NW)
cor(x,N)

和生成的栅格中位置x处保存的平均值。边缘单元将是NA,或者如果可能的话,标记用于计算与其接触的单元(3或5个单元)的平均相关性。 谢谢!

1 个答案:

答案 0 :(得分:6)

我不相信@ Pascal使用focal()的建议可行,因为focal()将单个栅格图层作为参数,而不是堆栈。这是最容易理解的解决方案。通过最小化为每个焦点单元格提取值的次数,可以提高效率:

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)