如何根据另一个栅格网格单元值对栅格进行子集化(分类)?

How to subset (classify ) raster based on another raster grid cells values?

如何根据给定示例中 r2 中的以下条件重新分类(子集)栅格 r1(与 r2 具有相同的维度和范围)。

条件:

即。我如何更改 r1 中的网格单元值,以便它给出对应于 >0.5 值网格单元的那些值及其在 r2 中每个方向的缓冲(周围)两个网格单元。

如果我只需要获取网格单元格 >0.5 我会很容易地通过以下代码获取,但是,我想提取 >0.5 值以及 2 周围的值网格单元也是如此。

示例计算代码为:

set.seed(150)
r1 <- raster(ncol=10, nrow=5) #Create rasters
values(r1) = round(runif(ncell(r1),5,25))
r2 <- raster(ncol=10, nrow=5)
values(r2) = round(runif(ncell(r2),0.1,1))

selfun <- function(x,y) {
  ifelse( x >0.5, y,0)
}  # It works only for >0.5 gridcells, i need this gridcells and its adjacent
  #two gridcells in each direction.
# it's like buffering the >0.5 grid cells with adjacent two grids and retaining corresponding grid cells values.

r3<-overlay(r2,r1,fun=selfun)
plot(r3)

谢谢。

我们可以使用 focal 函数创建一个显示感兴趣像素的蒙版,然后使用 mask 函数检索值。

我将创建我的示例,因为您创建的示例栅格对于演示来说太小了。

# Create example raster r1
set.seed(150)
r1 <- raster(ncol = 100, nrow = 50) 
values(r1) <- round(runif(ncell(r1), 5, 25))

r1 <- crop(r1, extent(-60, 60, -30, 30))

plot(r1)

# Create example raster r2
r2 <- raster(ncol = 100, nrow = 50)
values(r2) <- rnorm(ncell(r2), mean = -1)

r2 <- crop(r2, extent(-60, 60, -30, 30))

plot(r2)

第一步是处理 r2,将任何大于 0.5 的值替换为 1,将其他值替换为 NA

# Replace values > 0.5 to be 1, others to be NA
r2[r2 > 0.5] <- 1
r2[r2 <= 0.5] <- NA

plot(r2)

在使用focal函数之前,我们需要定义一个表示window的矩阵和一个函数

# Define a matrix as the window
w <-  matrix(c(NA, NA, 1, NA, NA, 
               NA, 1, 1, 1, NA,
               1, 1, 1, 1, 1, 
               NA, 1, 1, 1, NA,
               NA, NA, 1, NA, NA), ncol = 5)
# Define a function to populate the maximum values when w = 1
max_fun <- function(x, na.rm = TRUE) if (all(is.na(x))) NA else max(x, na.rm = na.rm)

然后我们可以应用focal函数。

r3 <- focal(r2, w = w, fun = max_fun, pad = TRUE)

plot(r3)

r3 是一个图层,显示我们想要来自 r1 的像素值。我们现在可以为此使用 mask 函数。

# Use the mask function extract values in r1 based on r3
r4 <- mask(r1, r3)
# Replace NA with 0
r4[is.na(r4)] <- 0

plot(r4)

r4是最终输出。