简体   繁体   English

在R中使用多元函数应用

[英]stackApply with multivariate function in R

I am looking to use stackApply() in the raster package and approx() to linearly interpolate a grid cell of one raster between a stack of rasters. 我正在寻找在栅格数据包中使用stackApply()stackApply()在一组栅格之间线性内插一个栅格的栅格像元。 I have written a similar function that does this calculation on a dataframe, but would like to preform this on the stack of rasters rather than rows in a dataframe. 我编写了一个类似的函数,该函数在数据帧上执行此计算,但是希望在栅格堆栈而不是数据帧中的行上执行此操作。 I have found previous examples of using stackApply() with a user defined function, but none that involve multiple variables. 我已经找到了在用户定义的函数中使用stackApply()的先前示例,但没有一个涉及多个变量。

In other words, I have a stack of rasters and a lone raster grid (they have matching extent and resolution). 换句话说,我有一堆栅格和一个单独的栅格网格(它们具有匹配的范围和分辨率)。 I want to "drill" through the stack, cell by cell, to create a vector of values and linearly interpolate the value of the matching grid cell in the lone raster with the stack-created vector. 我想逐个单元地在堆栈中“钻取”以创建值的向量,并使用堆栈创建的向量线性地对孤立栅格中的匹配网格像元的值进行插值。

My code is along the lines of... 我的代码遵循...

require(raster)
set.seed(42) 
x1 <- runif(100) 
x2 <- x1 
x3 <- x1 
x1[sample(1:100, 30)] <- NA 
x2[sample(1:100, 30)] <- NA 
x3[sample(1:100, 30)] <- NA 
r1 <- raster(matrix(x1, nrow=10, ncol=10)) 
r2 <- raster(matrix(x2, nrow=10, ncol=10)) 
r3 <- raster(matrix(x3, nrow=10, ncol=10)) 
s <- stack(r1, r2)

myfunc <- function(x,y){approx(x,c(0,1),y)}
newrast <- stackApply(stack,c(1,2), fun=myfunc(s,r3))

I am confused on how to pass multiple variables into the fun= argument in stackApply. 我对如何将多个变量传递给stackApply中的fun =参数感到困惑。 I am also unsure on the ind= argument. 我也不确定ind =参数。 I want to make sure that the function is being done through all layers, rather than on an entire layer individually and then repeated for each layer. 我想确保功能是在所有层上完成的,而不是在整个层上完成,然后对每一层重复进行。

Thank you! 谢谢!

I think that stackApply does not apply here. 我认为stackApply在这里不适用。 You would use calc instead. 您将使用calc代替。

For approx-like problems, you can consider raster::approxNA 对于类似问题,可以考虑使用raster::approxNA

s <- stack(r1, r2, r3)
x <- approxNA(s)

But if that does not work, you can do things like 但是,如果这样不起作用,您可以执行以下操作

f <- function(x) x[1] * sum(x[-1])
y <- calc(s, f)

alternatively, consider overlay 或者,考虑overlay

s <- stack(r1, r2)
z <- overlay(s, r3, fun=function(x, y) x * y)

(I would implement the function you are after, but I have no idea what you mean with "interpolate the value of the matching grid cell in the lone raster with the stack-created vector") (我将实现您想要的功能,但是我不知道“用堆栈创建的向量对孤立栅格中匹配的网格像元的值进行插值”是什么意思)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM