Find second highest value on a raster stack in R

后端 未结 1 924
无人共我
无人共我 2020-12-18 14:54

In R I can easily compute the max/min value of each cell in a georeferenced raster stack using the max/min commands.

set.seed(42)
require(raster)
r1 <- r         


        
相关标签:
1条回答
  • 2020-12-18 15:22

    You'll probably want to use calc(), adapting the code below to your precise situation. Just to show that it works as advertised, I've separately plotted layers formed by taking the highest, second highest, third, and fourth highest values found in each cell of the 4-layer RasterStack object.

    zz <- range(cellStats(rs, range))
    
    par(mfcol=c(2,2))
    plot(calc(rs, fun=function(X,na.rm) X[order(X,decreasing=T)[1]]), main="1st",zlim=zz)
    plot(calc(rs, fun=function(X,na.rm) X[order(X,decreasing=T)[2]]), main="2nd",zlim=zz)
    plot(calc(rs, fun=function(X,na.rm) X[order(X,decreasing=T)[3]]), main="3rd",zlim=zz)
    plot(calc(rs, fun=function(X,na.rm) X[order(X,decreasing=T)[4]]), main="4th",zlim=zz)
    

    Or, more compactly and efficiently, just construct a new raster stack holding the reordered values and then plot its layers:

    zz <- range(cellStats(rs, range))
    rs_ord <- calc(rs, fun=function(X,na.rm) X[order(X,decreasing=T)])
    
    par(mfcol=c(2,2))
    plot(rs_ord[[1]], main="1st", zlim=zz)
    plot(rs_ord[[2]], main="2nd", zlim=zz)
    plot(rs_ord[[3]], main="3rd", zlim=zz)
    plot(rs_ord[[4]], main="4th", zlim=zz)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题