2

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

Try this:

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

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.