Search code examples
rstackgisraster

How to get the number of unique values for each layer in a Large raster stack in R?


I have a large stack of raster which represent woodland patches (63 layers). I am trying to find a concise way of getting the number of unique values for each layer.

For one raster I have done this as below.

r1 <- raster(matrix(sample(1:100, 20), 10,10)) #create mock data
length(unique(r1)) #gives number of unique values 

But if I had a stack of 3 rasters as below is there a concise way of getting this information for each layer.

### mock data
r1 <- raster(matrix(sample(1:100, 20), 10,10))
r2 <- raster(matrix(sample(1:100, 50), 10,10))
r3 <- raster(matrix(sample(1:100, 10), 10,10))
### create raster stack
allrasters <- stack(r1, r2, 23)

Solution

  • You could use freq inside the raster package to obtain the frequency per pixel value for each layer and then just count the number of different values with nrow. Finally, you could transform the data from a list to a data.frame, in order to call it easier on further calculations.

    library(raster)
    as.data.frame(lapply(freq(allrasters), function(x) nrow(x)))
    
    #    layer.1 layer.2 layer.3
    # 1       20      50      10