I want to analyze a raster stack and determine the first layer in the stack that meets a condition for every pixel.
Here's a reproducible code example generating rasters and making a stack.
# Generate stack of random values r1 <- r2 <- r3 <- r4 <-r5 <- r6 <- r7 <- raster(ncol=10, nrow=10) r1 <- rpois(ncell(r1), 1) r2 <- rpois(ncell(r2), 1) r3 <- rpois(ncell(r3), 1) r4 <- rpois(ncell(r4), 1) r5 <- rpois(ncell(r5), 1) r6 <- rpois(ncell(r6), 1) r7 <- rpois(ncell(r7), 1) # stack them s <- stack(r1,r2,r3,r4,r5,r6,r7)
I want to analyze this stack to determine which layer is the first to meet a condition like: "Value = 1 for 3 consecutive layers" or "2 of last 3 layers have value = 1", for example.
Can you think of any function to do this?
If I run rasterToPoints I can convert the stack into a matrix with columns representing each layer, this may make things easier.
Once I determine the correct layer corresponding to each pixel, I then want an output raster with that layer number as the value for each pixel.
A somewhat similar question has been previously posted as Counting layer number of raster stack with value under some conditions and write it into output layer?, though that's counting the number of layers that meet a condition.