Replacing values between rasters

时间:2018-04-20 21:20:20

标签: r raster

I'm simplifying my question a bit, so hopefully, it makes sense.

I have three rasters that I'm working with.

library(raster)
LC <- raster("finalRRaster2018.tif")
nativeAET <- raster('kohala_aet_mm_ann_int.tif')
nonnativeAET <- raster('pred_AET.tif`)

The raster LC is a raster with landcover attribute values 1 being native landcover and 0 being non-native landcover.

The nativeAET and nonnativeAET are rasters of evapotranspiration under native species and nonnative species respectively. Both rasters have attributes between [0,15000]

What id like to do is replace all the values of 1 with the nativeAET values and all the values of 0 with the nonnativeAET values.

My idea is to transform the landcover raster (with values 1 or 0) to an AET raster (with values between 0 and 15000).

I used the following code

native <- values(LC) == 1
nonative <- values(LC) ==0
LC[native] <- values(nativeAET)[native]
LC[nonnative] <- values(nonnativeAET)[nonnative]

but when I plot my graphs, i get the warning number of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement length

and the plot looks something like this,

enter image description here

My problem is I would expect the resulting plot to not look as chunky. I feel like the rasters are not aligning properly but when i check the extent and dimensions of the rasters, they all seem to share the same projections.

Any help is greatly appreciated!

2 个答案:

答案 0 :(得分:1)

如果您提供了一些代码生成的示例数据,那么问题会更容易回答。

示例数据:

library(raster)
nativeAET <- nonnativeAET <- LC <- raster(ncol=4, nrow=4)
values(nativeAET) <- 1:16
values(nonnativeAET) <- 21:36
values(LC) <- c(rep(0,8), rep(1,8))

方法1:

AETnative <- mask(nativeAET, LC, maskvalue=1, updatevalue=0)
AETnonnative <- mask(nonnativeAET, LC, maskvalue=0, updatevalue=0)
AET <- AETnative + AETnonnative

方法2:

AET <- mask(nativeAET, LC, maskvalue=1)
AET <- cover(AET, nonnativeAET)

答案 1 :(得分:0)

假设nonative(一个"n")中的拼写错误得到纠正,您的代码应该可以正常工作(而且速度很快)。

错误可能来自栅格空间分辨率的差异。因此,ncell(LC) != ncell(nativeAET)ncell(LC) != ncell(nonnativeAET)。如果不是这种情况,则需要使用例如:

重新采样栅格
nativeAET <- resample(LC, nativeAET, method='ngb')
nonnativeAET <- resample(LC, nonnativeAET, method='ngb')

如果LC栅格中只有两个值(0和1),则可以通过执行以下操作来加速代码:

AET <- nativeAET 
AET[values(LC) == 0] <- values(nonnativeAET)[values(LC) == 0]