Problem with the "stackApply" function

Hello, I have a problem with the "stackApply" function from the raster-package. First I want to stack three raster layers (each layer has one band) - that works. And then I want to create a raster-object that shows in which of the three bands/layers the minimum value occurs (each pixel in the raster layers has a different value). But I get various error messages. Does anyone have an idea how I can solve the problem?
Thank you

min_which <- stackApply(stacktest, indices=1, fun=function(x, na.rm=NULL)which.min(x))

Error Messages:
Error in setValues(out, v) : values must be a vector
Error in is.infinite(v) : not implemented standard method for type 'list'

I think that what you are trying to do should work, if I understand you correctly.

Here is a small reproducible example. I am thinking something must be awry with one or more of the input rasters test1/test2/test3...

#> Loading required package: sp

# create three random layers with different possible maximum
randomRaster <- function(maxval) raster(matrix(floor(runif(1e5, 0, maxval)), 
                                               nrow = 100, ncol = 100))
test1 <- randomRaster(3)  # 1 intermediate
test2 <- randomRaster(2)  # 2 most common
test3 <- randomRaster(50) # 3 most rare

stack_test <- stack(test1, test2, test3)

# inspect
# this is your code exactly
min_which <- stackApply(stack_test, indices=1, fun = function(x, na.rm=NULL) which.min(x))

# appears to work as expected

Created on 2020-11-08 by the reprex package (v0.3.0)

Alright, I solved the problem with your help. Thank you very much!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.