Search code examples
rtime-seriesrasterrank

Ranking a raster time-series


I have a raster timeseries and I would like to rank the single pixel values according to the position in the TS. E.g.: timeseries (5 years) values: 3,5,2,8,7 so year 1 is 4, year 2 is 3, year 3 is 5 and so on. Output will be a stack that will have for each year the value of the pixel calculated as above

I have been able to order the raster values and create a new TS from higher to lower values but what I was looking for is not the ranked value but the position. This does not looks the right way

library(raster)
r <- raster(ncol=10, nrow=10)
r <- stack(lapply(1:5, function(i) setValues(r, runif(100, -0, 1000))))
names(r)<-c(1:nlayers((r)))
plot(r)


r_ord <- calc(r, fun=function(x,na.rm) x[order(x,decreasing=T)])
r_ord
plot(r_ord)

Any suggestion? Thanks


Solution

  • The original pixel values are being returned as you are using the order to index the original pixel values here x[order(x,decreasing=T)], which is effectively what the sort function returns. Use this code to return the order:

    library(raster)
    r <- raster(ncol=10, nrow=10)
    r <- stack(lapply(1:5, function(i) setValues(r, runif(100, -0, 1000))))
    names(r)<-c(1:nlayers((r)))
    plot(r)
    
    res <- calc(r,function(x) order(x,decreasing=T))
    plot(res)
    

    enter image description here