【发布时间】:2021-10-20 16:07:12
【问题描述】:
我正在尝试计算 3 x 中栅格单元 i 与其邻居 js(即 (j-i)^2)之间的差异的平方3 个邻域,然后计算这些差异的平均值并将结果分配给单元格 i。 我发现 this answer,由 Forrest R. Stevens 给出,接近我想要实现的目标,但我只有一个栅格(不是堆栈),包含 136710 个单元格(1 089 130 个与 adjacent 的组合 em> 函数),所以 for 循环将永远持续下去。
我想使用 raster 包中的焦点函数,因此 for 循环仅针对 3x3 矩阵运行,但它不适用于我。 这是一个使用我上面提到的 Forrest R. Stevens 代码的示例:
r <- raster(matrix(1:25,nrow=5))
r[] <-c(2,3,2,3,2,
3,2,3,2,NA,
NA,3,2,3,2,
NA,2,3,2,3,
2,3,2,3,NA)
## Calculate adjacent raster cells for each focal cell:
a <- raster::adjacent(r, cell=1:ncell(r), directions=8, sorted=T)
# Function
sq_dff<- function(w){
## Create column to store calculation:
out <- data.frame(a)
out$sqrd_diff <- NA
## Loop over all focal cells and their adjacencies,
## extract the values across all layers and calculate
## the squared difference, storing it in the appropriate row of
## our output data.frame:
cores <- 8
beginCluster(cores, type='SOCK')
for (i in 1:nrow(a)) {
print(i)
out$sqrd_diff[i] <- (r[a[i,2]]- r[a[i,1]])^2
print(Sys.time())
}
endCluster()
## Take the mean of the squared differences by focal cell ID:
r_out_vals <- aggregate(out$sqrd_diff, by=list(out$from), FUN=mean,na.rm=T)
names(r_out_vals)<- c('cell_numb','value')
return(r_out_vals$value)
}
r1 <- focal(x=r, w=matrix(1,3,3), fun=sq_dff)
如果我像这样应用它,该功能效果很好: r1
但是,当我将它应用到上面所写的焦点函数中时,它会返回一个栅格,其中只有中心的九个单元格的值,并且所有这些单元格都分配了相同的 0.67 值。
谢谢!
【问题讨论】:
标签: r