用另一个栅格中的值替换栅格中的值

Replace a value in a raster with the value from another raster

在下面的示例中,我试图用栅格 r2 中的相应像素值替换栅格 r 中的值 10:

library(raster)    

r <- raster(nrows=25, ncols=25, vals=round(rnorm(625, 3), 0)) #land-use/cover raster
r[ r > 2 ] <- NA
r[ r < 1 ] <- 10
plot(r)

r2 <- raster(nrows=25, ncols=25, vals=round(rnorm(625, 3), 0)) #land-use/cover raster
plot(r2)

我希望以下代码能够工作:

r3 <- overlay(r, r2, fun = function(x, y) { x[ x == 10 ] <- y ; return(x) })

...但是 returns 一个错误:

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun = FALSE, : cannot use this formula, probably because it is not vectorized

我确信部分问题出在叠加函数中的“<- y”。我尝试使用“<- y[ x == 10 ]”,但我仍然 运行 遇到同样的问题......有什么想法吗?提前致谢。

您需要将 [x=10] 替换为 10。 尝试使用以下代码。

r3 <- overlay(r, r2, fun = function(x, y) { x[ 10 ] <- y ; return(x) })

r3 <- overlay(r, r2, fun = function(x, y) { x[ 10 ] <- y[10] ; return(x) })

如果您在示例中使用随机值,我建议您也使用随机种子,以便它具有可重现性和可比性。

由于您的两个栅格具有相同的维度,您可以只使用逻辑索引。

这是一个小例子:

library(raster)

set.seed(42)

r <-setValues(raster(ncol=10,nrow=10),round(runif(100,1,10)))
r2 <-setValues(raster(ncol=10,nrow=10),round(runif(100,1,10)))

# create logical index (for later comparison)
ix <- r == 10

# returns FALSE, so r2 doesn't have any 10 where r has one
any(r[ix] == r2[ix])

r[ix] <- r2[ix]

# prints TRUE, so all values have been correctly replaced
all(r[ix] == r2[ix])

您也可以在一个简单的衬垫中进行更换:

r[r == 10] <- r2[r == 10]

(编辑:感谢@Nemesi)