I am using QGIS.

I have 20 large rasters showing land cover over 20 years (MCD12Q1). Each pixel contains a value between 1 and 17 that corresponds to a land cover class.

I am trying to create a new raster that shows how many unique land cover classes each pixel has experienced across the 20 yearly rasters. For example, if a pixel was forested, then became grassland for a few years, and then reverted back to forest, that pixel in the new raster would have a value of 2.

I am relatively new to all of this, but I've tried exploring online and asking others and haven't found a solution yet. I have tried using a loop to index each pixel across the rasters, then use the R unique and length commands to "count" unique values like this:

for (i in 1:nrow(layer2001)){
  for (j in 1:ncol(layer2001)){
    sub = as.numeric(unique(s[[1:20]][i,j]))
    sub = unique(sub)
    temp = as.numeric(length(sub))
    newrast[cellFromRowCol(newrast,i,j)][1] <- temp

but because of the size of the rasters this is not a solution. I have also been pointed towards the stackApply command but haven't been able to use it successfully.

1 Answer 1


You can use Menu Processing > Toolbox > Cell statistics. For Statistics, select Variety (count of unique values). See details in the documentation.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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