R: apply a function of type () to two 2-dimensional arrays

I am trying to find a function of type apply () that can run a function that runs on two arrays instead of one.

View like:

apply(X1 = doy_stack, X2 = snow_stack, MARGIN = 2, FUN = r_part(a, b))

The data is a stack of tape arrays of Landsat tiles that are stacked using rbind. Each row contains data from one fragment, and in the end I need to apply a function for each column (pixel) of data in this stack. One of these stacks contains whether each pixel contains snow on it or not, and the other stack contains the day of the year for this line. I want to run a classifier (rpart) on each pixel and tell it a day free of snow for each pixel.

What I'm doing now is pretty stupid: mapply(paste, doy, snow_free)combines the day of the year and the snow status together for each pixel as a string, apply(strstack, 2, FUN)launches a classifer on each pixel and inside the apply function, I 'blast each line with strsplit. As you can imagine, this is pretty inefficient, especially at 1 million pixels x 300 tiles.

Thank!

+3
source share
4 answers

I would not think too much. For the loop, there may be everything you need.

out <- numeric(n)
for(i in 1:n) {
  out[i] <- snow_free(doy_stack[,i], snow_stack[,i])
}

Or, if you do not want to do accounting yourself,

sapply(1:n, function(i) snow_free(doy_stack[,i], snow_stack[,i]))
+8
source

I just ran into the same problem, and if I clearly understood the question, I might have solved it using mapply.

10x10, .

set.seed(1)
X <- matrix(runif(100), 10, 10)
set.seed(2)
Y <- matrix(runif(100), 10, 10)

, . -, X Y, data.frame. , data.frame list, - . mapply() , list. .

res.row <- mapply(function(x, y){cor(x, y)}, as.data.frame(t(X)), as.data.frame(t(Y)))
res.row[1]
     V1 
0.36788

,

cor(X[1,], Y[1,])
[1] 0.36788

t():

res.col <- mapply(function(x, y){cor(x, y)}, as.data.frame(X), as.data.frame(Y))

, , , X Y , (.. ). , , .

+2

Wouldn't it be more natural to implement this as a raster stack? With the package, rasteryou can use whole rasters in functions (for example, ras3 <- ras1^2 + ras2), and also extract one cell value from XY coordinates or many cell values ​​using a block mask or polygon.

+1
source

applycan work with higher sizes (i.e. elements list). Not sure how your data is set up, but something like this might be what you are looking for:

apply(list(doy_stack, snow_stack), c(1,2), function(x) r_part(x[1], x[2]))
-1
source

Source: https://habr.com/ru/post/1793964/


All Articles