是否可以将函数应用于一个栅格堆栈并更改另一个栅格堆栈中的值

Is it possible to apply function over one stack of rasters and change values in another

提问人:Waqas Ahmad 提问时间:11/17/2023 最后编辑:Waqas Ahmad 更新时间:11/17/2023 访问量:28

问:

假设我们有 3 个栅格堆栈,如下所示:

library(terra)

r <- rast(ncols=2, nrows=2)

r1 <- setValues(r, c(0.7,0.2,0.5,0.9))
r2 <- setValues(r, c(0.6,0.18,0.3,0.7))
r3 <- setValues(r, c(0.3,0.24,0.2,0.1))
r4 <- setValues(r, c(0.18,0.4,0.3,0.3))
r5 <- setValues(r, c(0.3,0.5,0.35,0.4))
r6 <- setValues(r, c(0.5,0.6,0.7,0.6))
r7 <- setValues(r, c(0.8,0.9,0.8,0.8))
r8 <- setValues(r, c(0.7,0.7,0.5,0.6))
r9 <- setValues(r, c(0.5,0.5,0.4,0.4))
r10 <- setValues(r, c(0.22,0.18,0.3,0.25))
r11 <- setValues(r, c(0.1,0.4,0.3,0.3))
r12 <- setValues(r, c(0.4,0.5,0.3,0.4))

# 1st Stack
s <- c(r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12)

#and some other variables:
temp <- c(2.3,2.1,2.2,3,3.5,5,5.6,7,10,8,3,1)
rain <- c(0,0,50,100,0,0,170,0,250,150,0,0)

# 2 more Stacks just like 1st stack s with NA values
SM1 <- EA <- s
SM1[] <- EA[] <-NA

# Value 1 inserted at different positions as a starting point for calculations to 
# begin for individual cells. As stack has 4 cells per layer and each cell has 
# different starting point in time. Each layer represent a month so 12 layers for a year.
SM1[1][4:12] <- 1
SM1[2][3:12] <- 1
SM1[3][5:12] <- 1
SM1[4][2:12] <- 1

f <- function(x){
# find index of point from where calculations should begin
st <- which(x == 1)
# fill SM[st+1] with calculated value
x[st+1] <- rain[st+1]/temp[st+1]
# Now this is tricky, how to apply this? EA stack gets filled with some other calculated value
EA[st] <- x[st]/(temp[st]-rain[st])
# Return both x and EA 
x
EA
}

SM <- app(SM1,f)

所以,这是我试图做的复杂事情的最小可重复的例子。我正在避免 for 循环,但堆栈 SM 被计算出来,然后堆栈 EA 被填充。如果堆栈 SM 的第 5 个单元格被填充,则 EA 堆栈的第 4r 个单元格被填充,依此类推。

是否可以在应用程序函数或其他方法中执行此类操作。或者,我使用 cbind 和 write 函数加入两个堆栈,该函数运行到各个堆栈的 nlyr 并使用索引来填充其他堆栈,例如:

C <- cbind(SM,EA)
C[i] <- calculations....
C[nlyr(SM) + i -1] <- calculations....
R 栅格 Terra

评论


答: 暂无答案