I have a list of raster stacks named r.lst. I need to calculate the difference between max(r.lst[[i]]) (stacked rasters) and every raster layer of that raster stack. However, I want to do this conditionally for each pixel by considering which.max(r.lst[[i]]). So that each cell in deducted from its previous max not the next. Please see below example:
# example data-------------------------------------------
set.seed(123)
#our list of rasters
r.lst <- as.list(1:3)
# setting up list pf raster stacks
r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = runif(36, 1, 5))
r.lst[[1]] <- stack(lapply(1:8, function(i) setValues(r1,runif(ncell(r1)))))
r.lst[[2]] <- stack(lapply(1:6, function(i) setValues(r1,runif(ncell(r1)))))
r.lst[[3]] <- stack(lapply(1:7, function(i) setValues(r1,runif(ncell(r1)))))
I can easily calculate the difference for every single layer within each three raster stack of r.lst[[i]] as below:
# compute the difference between max and min
x1 <- list()
x2 <- list()
xx <- list()
for (i in 1:length(r.lst)) {
x1[[i]] <- max(r.lst[[i]])
x2[[i]] <- which.max(r.lst[[i]])
x <- list()
for (j in 1:nlayers(r.lst[[i]])){
x[[j]] <- x1[[i]]-r.lst[[i]][[j]]
}
xx[[i]] <- stack(x)
print(i)
}
par(mfrow=c(1,4), oma=c(0,0,0,1), mai=c(0.7,0.4,0.7,0.4))
plot(r.lst[[1]][[1]], main="Input.Raster") #Input from stack
plot(x1[[1]], main="Max") #Max of stack
plot(x2[[1]], main="Max.Index") #Index of Max value in raster stack
plot(xx[[1]][[1]], main="Results") #OUTPUT (not what I wanted)
But this is not what I want. I need to consider which.max(r.lst[[i]]) in each round of calculation so that if the index of a layer under consideration is bigger than the index of which.max(r.lst[[i]]) we calculate the difference, if not I need to calculate the difference considering earlier max layer. Simply the calculation for every raster layer is only valid compared to its earlier max not the next.

maxthat is initiated before the for-loop and increases in every iteration only ifmax(r.lst[[i]]) > max. Or is this not what you want? - symbolrushwhich.max(r.lst[[i]])andr.lst[[i]][[j]]index itself. Simplemax(r.lst[[i]]) > maxwont really help here. - Majid