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

Lil*_*ure 3 r raster rasterizing r-raster

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

状况:

  • 如果的网格单元的值r2>0.5,保留对应值和相邻的2个网格细胞旁0.5的值(即,具有值缓冲网格单元>0.5r2,以在所有方向上环绕两个栅格)中r1并改变其它值为0。

IE。我如何更改网格单元格的值,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)
Run Code Online (Sandbox Code Playgroud)

谢谢你。

www*_*www 6

我们可以使用该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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

# 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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

第一步是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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

# 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)
Run Code Online (Sandbox Code Playgroud)

然后我们可以应用该focal功能。

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

plot(r3)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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)
Run Code Online (Sandbox Code Playgroud)

r4 是最终的输出。

在此处输入图片说明