创建新栅格,每个像素都填充了特定速率堆栈图层中的值



我希望创建一个新栅格,每个像素都填充了来自特定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)

您可以使用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

最新更新