You can use which.max
directly
Example data
library(raster)
f <- stack(system.file("external/rlogo.grd", package="raster"))
s <- stack(f/2, f, f, f)
nlayers(s)
#[1] 12
# add some `NA`s
s[[12]] <- setValues(s[[12]], NA)
(r <- which.max(s))
#class : RasterLayer
#dimensions : 77, 101, 7777 (nrow, ncol, ncell)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#crs : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
#source : memory
#names : layer
#values : 1, 6 (min, max)
As Jeffrey Evens pointed out, you can also do:
rc <- calc(s, which.max)
The reason that you can use whiches.max
with no more then 9 layers (it could have been 10) is that it also returns ties:
(rr <- whiches.max(s[[1:9]]))
#class : RasterLayer
#dimensions : 77, 101, 7777 (nrow, ncol, ncell)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#crs : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m #+no_defs
#source : memory
#names : layer
#values : 47, 123456789 (min, max)
47
means that layers 4 and 7 both have the maximum value.
Also note that which.max
always ignores NA
s:
which.max(c(NA, 1:5, NA, 3))
#[1] 6
And with terra
:
library(terra)
f <- system.file("ex/logo.tif", package="terra")
x <- rast(c(f, f, f, f))
x[[1:3]] <- x[[1:3]] / 2
which.max(x)
#class : SpatRaster
#dimensions : 77, 101, 1 (nrow, ncol, nlyr)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
#source : memory
#name : which.max
#min value : 1
#max value : 6