I have 12 land cover maps, and I would like to calculate the mode to each pixel of the 12 maps (they have the same resolution and dimension). I mean, the final map would be the mode for each pixel of the 12 land cover maps.

I already tried using this GRASS module (raster calculator): r.mapcalc raster_mode = mode(raster1, raster2,...raster12), but I just obtained an empty map. I also tried with raster calculator of Qgis, but it seems it hasn't the mode function.

I can use GRASS, Qgis, R, Python...(Open Source).


I am assuming that by mode you mean the most frequent class? You can use the R function "table" to calculate the frequencies of a vector.

x <- c(1,1,2,3,4,4,4,4)

Then use which.max to return the class associated with the most frequent class. To return the actual class name you need to wrap the statement in names.

which.max( table(x) )
names( which.max( table(x) ) )

If you ever need class percents, you can pass the frequency table to the prop.table function.


Now you ask, how does this apply to rasters? You can vectorize the problem using calc or overlay. In this case, because we do not have to specifically index each raster, the calc option is a far simpler approach in writing a function for returning the majority class.

Here we write a function, using the above example, that returns the most frequent values, at the cell level, across all the rasters. The only addition is as.numeric because we need the resulting values assigned to the raster to be numeric.

maj.class <- function(x) { as.numeric( names( which.max( table(x) ) ) ) }

We then dummy up some example data, 4 rasters each with 4 classes, and pass our function to calc.

r1 <- r2 <- r3 <- r4 <- raster(nrows=50, ncols=50)
r1[] <- round(runif(ncell(r1),1,4),0)
r2[] <- round(runif(ncell(r2),1,4),0)
r3[] <- round(runif(ncell(r3),2,6),0)
r4[] <- round(runif(ncell(r4),4,8),0)
( r <- stack(r1,r2,r3,r4) )

( mclass <- calc(r, maj.class) )
  • 2
    You can also do: mclass <- calc(r, modal) – Robert Hijmans Mar 15 '15 at 22:28

Jeffrey's answer works perfectly but the GRASS solution is also an option. I used r1, r2, r3 and r4 Jeffrey's raster for producing the 'mode' raster in QGIS-GRASS. The GRASS command was:

r.mapcalc mode="mode(r1,r2,r3,r4)"

At the Image below, I chose an arbitrary point to illustrate, with Value Tool Plugin, that the pixel value in the resultant map is the 'mode' of pixel values of r1, r2, r3 and r4.

enter image description here

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.