【问题标题】:How to subset (classify ) raster based on another raster grid cells values?如何根据另一个栅格网格单元值对栅格进行子集(分类)?
【发布时间】:2018-08-06 22:12:09
【问题描述】:

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

条件:

  • 如果r2的网格单元格值为>0.5,则保留对应的值和相邻的2个网格单元格旁边的0.5个值(即将r2中值为>0.5的网格单元格缓冲到周围的两个网格中所有方向)在r1 并将其他值更改为0。

即。如何更改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)

谢谢。

【问题讨论】:

    标签: r raster r-raster rasterizing


    【解决方案1】:

    我们可以使用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函数之前,我们需要定义一个代表窗口的矩阵和一个函数。

    # 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 是最终输出。

    【讨论】:

    • 谢谢,但是窗口矩阵是怎么定义的?
    • 您可以打印矩阵 w 并查看结构。你说你想要相邻的两个网格单元。我认为这可能意味着所有方向(上、下、左、右),但我不确定对角线的情况。我的示例矩阵假设对角线有一个单元格,但您可以根据需要修改矩阵。
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多