简体   繁体   English

R focus(栅格软件包):如何将过滤器应用于背景数据的子集?

[英]R focal (raster package): how to apply filter to subsets of background data?

I was wondering if any of you could help me with the following task dealing with the focal() function in the R raster package. 我想知道是否有人可以帮助我完成以下处理R栅格数据包中的focus()函数的任务。

By default, the focal() function will run through each cell of a given raster ('background' raster hereafter) and apply a given function to the neighboring values as defined by a user-defined moving window. 默认情况下,focus()函数将遍历给定栅格(以下称为“背景”栅格)的每个像元,并将给定函数应用于用户定义的移动窗口所定义的相邻值。 In order to optimize and speed up my computation on large rasters/study areas, I would like to apply this function (filter) only when the 'background' raster has some values (eg greater than zero) within the extent covered by the 'moving window' and skip all the other focal cells. 为了在大型栅格/研究区域上优化并加快计算速度,我仅在“背景”栅格具有“移动”所覆盖范围内的某些值(例如,大于零)时才应用此函数(过滤器)窗口”并跳过所有其他焦点单元。 This way, the filter would not spend time computing any focal value where there is no need to. 这样,过滤器将无需花费时间来计算不需要的任何焦点值。

Below a reproducible small example and in-line comments: 下面是一个可复制的小示例和在线注释:

library(raster)

x <- matrix(1:25, ncol=5)
x[c(1,2,3,6,7,8,11,12,13)] <- 0
r <- raster(x)

#Apply filter to focal cells and return values using a 3x3 moving window...ONLY IF 
#ALL values found within the window are > 0. Skip focal cell otherwise.

r3 <- focal(r, w=matrix(1/9,nrow=3,ncol=3), FUN=sum)

How should I change this function to have the desired outcome? 我应该如何更改此功能以达到预期的效果?

The windows slide operates @ all focal pixels locations. 窗口幻灯片在所有焦点像素位置均起作用。 Skipping/Jumping locations is not possible. 无法跳过/跳转位置。 However, you can check, whether all the elements/matrix cells satisfy your threshold condition as below: 但是,您可以检查是否所有元素/矩阵单元格都满足您的阈值条件,如下所示:

myfunc = function (x){
  if(all(x > threshold)){
    print(x)
    x = sum(x)
  }else{
    x = 0}
}
r3 <- focal(x=r>1, w=matrix(1/9,nrow=3,ncol=3), fun=sum)

I'm not sure it would be any faster, but you could also check if the center cell adheres to some criteria (eg is NA or >0). 我不确定会不会更快,但是您也可以检查中心单元格是否符合某些条件(例如NA或> 0)。 This way the focal calculation will only run when it meets those criteria. 这样,焦点计算仅在满足这些条件时才运行。

w=matrix(1,5,5)

skipNA_avgFunc <- function(x) {

  # general definition of center cell for weight matrices with odd dims
  center <- x[ceiling(length(x)/2)]

  if (is.na(center)) { # handle NA values
    return(center)
  }

  else if (center >= 0) { # calculate mean
    mean(x, na.rm=TRUE)
  }
}
r3 <- focal(r, w=w, fun=skipNA_avgFunc, pad=TRUE, padValue=NA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM