rfrequencyraster

How to pick the most frequent values (mode) from a raster stack


I have four layers in a raster stack and want to pick the most frequent value in each cell among the four layers.

Here is the dataset and code:

require(raster)
a <- raster(matrix(c(12,11,11, 
                     NA,11,11,
                     11,11,13),nrow=3))

b <- raster(matrix(c(12,12,12,
                     NA,12,12,
                     14,12,13),nrow=3))

c <- raster(matrix(c(13,9,13,
                     NA,13,13,
                     13,NA,13),nrow=3))

d <- raster(matrix(c(10,10,10,
                     NA,10,10,
                     10,10,10),nrow=3))

stk <- stack(a,b,c,d)

I wonder if it is possible to do it with code something like?

which.freqV <- function(x, ...){
   ???
}

max <- stackApply(stk,1,which.freqV,na.rm=NULL)

Solution

  • I had to this in my scripts (calculating the mode of a stack) and found something that works perfectly:

      Mode <- function(x) {
        ux <- unique(x)
        ux=ux[!is.na(ux)]
        ux[which.max(tabulate(match(x, ux)))]
      }
      layers_mode=calc(stack, fun=Mode)
    

    Now, if you want to calculate the frequency of the mode for each cell, use this:

      ###calculate proportion of layers that have mode value as measure of uncertainty
      Mode_count <- function(x) {
        ux <- unique(x)    
        ux=ux[!is.na(ux)]
        mode=ux[which.max(tabulate(match(x, ux)))]
        sum(x==mode, na.rm=T)
      }
      layers_mode_freq=calc(stack, fun=Mode_count)