Home > other >  Extract values from a certain layer in a stack based on pixel value of another raster
Extract values from a certain layer in a stack based on pixel value of another raster

Time:10-26

Suppose I have a raster layer r0 that the values range from 1: nlayers s. I need to extract values from the bands s that matches the pixel values from layer r0. For example, if a pixel value in r0 is 2 I want the value of the exact same pixel from band 2 in stacked layers s and so forth. So the final output would be only one layer representing the values from layer s based on layer r0. I hope I could explain the problem properly.

library(raster)

r <- raster(nrow=5, ncol=5)
r0 <- setValues(r, round(runif(25,min = 1, max = 10)), 0)




r1 <- setValues(r, runif(ncell(r)))
r2 <- setValues(r, runif(ncell(r)))
r3 <- setValues(r, runif(ncell(r)))
r4 <- setValues(r, runif(ncell(r)))
r5 <- setValues(r, runif(ncell(r)))
r6 <- setValues(r, runif(ncell(r)))
r7 <- setValues(r, runif(ncell(r)))
r8 <- setValues(r, runif(ncell(r)))
r9 <- setValues(r, runif(ncell(r)))
r10 <- setValues(r, runif(ncell(r)))


s <- stack(r1, r2, r3, r4,r5, r6,r7,r8,r9,r10)

CodePudding user response:

See terra::selectRange

example data

library(terra)
r <- rast(ncols=10, nrows=10)
values(r) <- 1
s <- c(r, r 2, r 5)
s <- c(s, s)
set.seed(1)
values(r) <- sample(3, ncell(r), replace=TRUE)

Solution

x <- selectRange(s, r)
  • Related