【问题标题】:Conditionally calculating the difference between max(raster) and each raster layer of raster stack有条件地计算 max(raster) 与栅格堆栈的每个栅格层之间的差异
【发布时间】:2019-05-02 06:11:32
【问题描述】:

我有一个名为r.lst 的栅格堆栈列表。我需要计算max(r.lst[[i]])(堆叠栅格)和该栅格堆栈的每个栅格层之间的差异。但是,我想通过考虑which.max(r.lst[[i]]) 有条件地为每个像素执行此操作。这样每个单元格从其 previous 最大值中扣除而不是下一个。请看下面的例子:

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

我可以很容易地计算出r.lst[[i]] 的每三个光栅堆栈中每一层的差异,如下所示:

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

但这不是我想要的。我需要在每一轮计算中考虑which.max(r.lst[[i]]),以便如果所考虑的层的索引大于which.max(r.lst[[i]]) 的索引,我们计算差异,如果不是,我需要考虑较早的最大层来计算差异。简单地说,每个栅格图层的计算仅与其之前的最大值相比才有效,而不是下一个。

【问题讨论】:

  • TL;博士。但我的第一印象是你只需要一个额外的变量max,它在 for 循环之前启动,并且只有在max(r.lst[[i]]) &gt; max 时才会在每次迭代中增加。或者这不是你想要的?
  • @symbolrush 感谢您的帮助。这不是我想要的。该条件将基于which.max(r.lst[[i]])r.lst[[i]][[j]] 索引本身的相应单个栅格单元。简单的max(r.lst[[i]]) &gt; max 在这里不会有什么帮助。

标签: r list max raster


【解决方案1】:

我相信您正在寻找类似下面的内容。

示例数据

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

解决方案

xx <- list()
for (i in 1:length(r.lst)) {
    xx[[i]] <- cummax( r.lst[[i]] ) -  r.lst[[i]]
}

即可以使用cummax获取之前值的最大值(包括当前值)

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

【讨论】:

  • 谢谢罗伯。我不知道cummax。那么为什么所有堆栈的第一个栅格总是空的呢?我试图用Max.Index 栅格从我的脚本中屏蔽每个xx,以仔细检查这些值,您的解决方案非常完美。但是,我对每个堆栈的第一个栅格总是完全空的感到困惑。
  • 第一层只有零,因为当只考虑该层时,输入第一层的值总是与最大值相同。没有其他值可以考虑,因为没有更早的值(层)。
猜你喜欢
  • 2018-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多