Search code examples
rmatrixoverlayrasterr-raster

Raster overlay from a matrix


I have a matrix of 100 raster layers and I'd like to create one new layer that is the average. I understand if there were two layers I could simply use the overlay function or perhaps just use c <- mean (a, b). However, I'm not sure how to proceed with the matrix.

Here is sample of the matrix:

[[1]]
class       : RasterLayer 
dimensions  : 175, 179, 31325  (nrow, ncol, ncell)
resolution  : 1, 1  (x, y)
extent      : 0, 179, 0, 175  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : 0, 100  (min, max)

I have tried

a.avg <- mean (a.total[,])

and I receive the error argument is not numeric or logical: returning NA


Solution

  • I assume you have a list of rasterLayers ( or perhaps a stack ). If you already have a stack, skip step one, but I assume you have a list not a matrix which I have called mylistofrasters...

    #1 - Get all rasters in the list into a stack
    mystack <- do.call( stack , mylistofrasters )
    
    #2 - Take mean of each pixel in the stack returning a single raster that is the average
    mean.stack <- calc( mystack , mean , na.rm = TRUE )