【问题标题】:R focal function: Calculate square of difference between raster cell and neighborhood and find the mean value for a 3x3 windowR 焦点函数:计算栅格单元和邻域之间的差平方并找到 3x3 窗口的平均值
【发布时间】: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


    【解决方案1】:

    你可以试试这个:

    library(terra)
    r <- rast(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)
            
    f <- function(x) {
        mean((x[-5] - x[5])^2, na.rm=TRUE)
    }
    
    rr <- focal(r, 3 ,f)
    plot(rr)
    text(rr, dig=2)
    

    【讨论】:

    • 非常感谢您的回答,@Robert Hijmans!我不知道 terra 包,它很棒而且运行速度超级快。我只做了一个小的调整:我添加了matrix(1,3,3)和pad=T,所以我使用了:rr
    • 不客气。如果 r 是 RasterLayer(然后您没有使用 terra 包),则需要进行这些调整
    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 2014-03-04
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2014-07-26
    相关资源
    最近更新 更多