Cecile
Cecile

Reputation: 535

Create new raster with each pixel filled with the value from specific raterstack layers

I wish to create a new raster with each pixel filled with the value from a specific raterstack layer (based on the layers IDs). The code below should clarify what I am trying to do. Thank you very much for your help!

# 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)

Upvotes: 0

Views: 54

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47536

You can use the stackSelect method for that

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

Upvotes: 1

Related Questions