创建一个新的栅格,每个像素都填充有特定raterstack图层中的值

时间:2018-10-20 03:47:08

标签: stack gis raster

我希望创建一个新的栅格,每个像素都填充有来自特定的raterstack图层(基于图层ID)的值。下面的代码应阐明我要做什么。非常感谢您的帮助!

# stack of layers
b<-raster(ncol=2,nrow=2, xmn=-10, xmx=10, ymn=-10, ymx=10)
c<-raster(ncol=2,nrow=2, xmn=-10, xmx=10, ymn=-10, ymx=10)
d<-raster(ncol=2,nrow=2, xmn=-10, xmx=10, ymn=-10, ymx=10)
b[]<-c(2,4,5,-10)
c[]<-c(3,1,5,5)
d[]<-c(5,4,3,6)
stk <- stack(b,c,d)

# indication of from which layer (layer 1, 2 or 3) the pixel value should come from
layerID<-raster(ncol=2,nrow=2, xmn=-10, xmx=10, ymn=-10, ymx=10)
layerID[]<-c(1,2,3,2)
plot(layerID)

#create a new raster with each pixel filled in with the right value
#problem - the code below doesn't work
newraster <- layerID
newraster[newraster==1] <- stk[[1]] #should be filling the pixels with values equal to 1 with values for the same pixels from layer 1
newraster[newraster==2] <- stk[[2]]
newraster[newraster==3] <- stk[[3]]

#What the final result should look like
final<-raster(ncol=2,nrow=2, xmn=-10, xmx=10, ymn=-10, ymx=10)
final[]<-c(2,1,3,5)

1 个答案:

答案 0 :(得分:1)

您可以为此使用stackSelect方法

library(raster)
b <- raster(ncol=2, nrow=2, xmn=-10, xmx=10, ymn=-10, ymx=10, vals=10)
c <- setValues(b, 11)
d <- setValues(b, 12)
stk <- stack(b, c, d)   
layerID <- setValues(b, c(1, 2, 3, 2))

x <- stackSelect(stk, layerID)
values(x)
#[1] 10 11 12 11