Reclassify a raster based on 2 rasters

喜夏-厌秋 提交于 2019-12-25 02:28:06

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/49674917/reclassify-a-raster-based-on-2-rasters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!