问题
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.
回答1:
I believe you are looking for something like the below.
Example data
library(raster)
set.seed(123)
r <- raster(res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5)
r.lst <- list()
r.lst[[1]] <- stack(lapply(1:8, function(i) setValues(r, runif(ncell(r)))))
r.lst[[2]] <- stack(lapply(1:6, function(i) setValues(r, runif(ncell(r)))))
r.lst[[3]] <- stack(lapply(1:7, function(i) setValues(r, runif(ncell(r)))))
Solution
xx <- list()
for (i in 1:length(r.lst)) {
xx[[i]] <- cummax( r.lst[[i]] ) - r.lst[[i]]
}
That is, you can use cummax
to get the max value of the prior values (including the current value)
x <- c(1:3, 3:1, 4, 3)
cummax(x)
#[1] 1 2 3 3 3 3 4 4
x - cummax(x)
#[1] 0 0 0 0 -1 -2 0 -1
来源:https://stackoverflow.com/questions/55946554/conditionally-calculating-the-difference-between-maxraster-and-each-raster-lay