# How to find the second highest value in a rasterStack in R

I have a rasterStack of rasters representing count data. I want to return a single raster whose values are the index of the raster with the second highest value for each cell. (I used which.max for the highest value.)

I'm using the raster package in R, but could use ArcGIS too. Thanks!

This works for identifying the raster with the max value:

``````set.seed(123)
library(raster)
r1 <- raster(nrows=10, ncols=10)
r2=r3=r4=r1
r1[]= runif(ncell(r1))
r2[]= runif(ncell(r1))+0.2
r3[]= runif(ncell(r1))-0.2
r4[]= runif(ncell(r1))+0.5

rs=stack(r1,r2,r3,r4)
plot(rs)

rs.max<-which.max(rs)
plot(rs.max)
``````

Try this:

`````` rs.secondMax <- calc(rs, fun=function(X,na.rm) which.max(X[X!=max(X)]))
``````

Using indexing on sort results you can pull any value in the vector.

``````( x = runif(20,1,10) )
sort(x)[length(x)-1]
``````

Using this logic you can pass the sort index to raster calc. The calc function treat stacked and brick object as individual vectors associated with each pixel.

``````rs2v <- calc(rs, fun=function(x) { sort(x)[length(x)-1] } )
plot(rs2v)
``````