根据2个栅格重新分类栅格 [英] Reclassify a raster based on 2 rasters

查看:116
本文介绍了根据2个栅格重新分类栅格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有两个具有相同空间范围的栅格(r1r2),我想创建一个以r1r2中的值为条件的栅格(r3) .我可以设置矩阵并使用raster::reclassify,但只能使用其中一个栅格进行这项工作.我正在寻找在两个栅格上执行此操作的有效方法.例如(请参阅下文),如果r1 = 0r2 < 2r3 = 0.5,但如果r1 = 1r2 < 2r3 = .8.然后,如果r1 = 0r2 > 2r3 = 0.7,但如果r1 = 1r2 > 2r3 = .9(我还有更多条件要在实际数据上使用).这是代码形式的示例.

I have two rasters (r1 and r2) in R with the same spatial extent and I'd like to create a raster (r3) that is conditional on values in r1 and r2. I can set up a matrix and use raster::reclassify, but I can only make this work using one of the rasters. I'm looking for an efficient way to do this on the two rasters. For example (see below) if r1 = 0 and r2 < 2, r3 = 0.5, but if r1 = 1 and r2 < 2, r3 = .8. Then if r1 = 0 and r2 > 2, r3 = 0.7, but if r1 = 1 and r2 > 2, r3 = .9 (I have several more conditions that I'd like to use on the real data). Here is that example in code form.

    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. 

我看了其他类似的问题,但没有找到我一直在寻找的解决方案.感谢您的帮助.

I looked at other similar questions and I didn't find exactly the solution I was looking for. I appreciate your help in advance.

推荐答案

如果r1r2具有可比性,则可以仅使用逻辑索引.如果您有大量(或不同数量)的条件,这可能会有点乏味,但是对于此示例,它确实可以工作:

If r1 and r2 are comparable, you can just use logical indexing. This might get a bit tedious if you have a ton (or a varying amount) of conditions, but for this example it certainly works:

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)

这篇关于根据2个栅格重新分类栅格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆