基于2个栅格重新分类栅格

时间:2018-04-05 14:29:23

标签: r gis raster

我在R中有两个栅格(r1r2)具有相同的空间范围,我想创建一个以值为条件的栅格(r3)在r1r2中。我可以设置一个矩阵并使用raster::reclassify,但我只能使用其中一个栅格来完成这项工作。我正在寻找一种在两个栅格上实现这一目标的有效方法。例如(见下文)r1 = 0r2 < 2r3 = 0.5r1 = 1r2 < 2r3 = .8。然后,如果r1 = 0r2 > 2r3 = 0.7,但是如果r1 = 1r2 > 2r3 = .9(我还有几个条件,我是&#39;} d喜欢在真实数据上使用)。这是代码形式的例子。

    library(raster)
    # create two random rasters
    r1 <- raster(matrix(rbinom(16, size=1, prob=.5), nrow=4))
    r2 <- raster(matrix(rpois(16, 2), nrow=4))
    # check that spatial extent is the same
    extent(r1) == extent(r2)

    # here is a reclassify matrix if r1==1
    reclass_m1 <- matrix(
      c(0,2,.8,
        3,5,.9
     ), ncol=3, byrow=TRUE
    )
    # reclassify matrix if r1==0
    reclass_m0 <- matrix(
      c(0,2,.5,
        3,5,.7
      ), ncol=3, byrow=TRUE
    )

    # so if r1==1,  I would want 
    r3 <- reclassify(r2, reclass_m1)

    # if r1==0, I would want 
    r3 <- reclassify(r2, reclass_m0)
    # but I want a single r3 that does this process consistently. 

我查看了其他类似的问题,但我没有找到我正在寻找的解决方案。我提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果r1r2具有可比性,您可以使用逻辑索引。如果您有大量(或不同数量)的条件,这可能会有点乏味,但对于这个例子,它确实有效:

library(raster)
# create two random rasters
r1 <- raster(matrix(rbinom(16, size=1, prob=.5), nrow=4))
r2 <- raster(matrix(rpois(16, 2), nrow=4))
# check that spatial extent is the same
extent(r1) == extent(r2)

plot(r1)
plot(r2)

# create r3 from r1
r3 <- raster(r1)

# fill based on conditions

r3[r1 == 0 & r2 < 2] <- 0.5
r3[r1 == 1 & r2 < 2] <- 0.8
r3[r1 == 0 & r2 > 2] <- 0.7
r3[r1 == 1 & r2 > 2] <- 0.9


r3

# class       : RasterLayer 
# dimensions  : 4, 4, 16  (nrow, ncol, ncell)
# resolution  : 0.25, 0.25  (x, y)
# extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
# coord. ref. : NA 
# data source : in memory
# names       : layer 
# values      : 0.7, 0.8  (min, max)