简体   繁体   中英

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

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. I am also unsure on the ind= argument. 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. You would use calc instead.

For approx-like problems, you can consider 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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