Question

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

Was it helpful?

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 )

OTHER TIPS

This answer is similar to the @SimonO101's answer using a simpler code.

First, let's build a list of RasterLayer (you can skip this step if you already have the list):

library(raster)

r <- raster(nrow=10, ncol=10)
r <- init(r, runif)
lr <- lapply(1:8, function(i)r)

The raster package defines an stack method for lists, so you can use it directly without do.call:

s <- stack(lr)

Besides, there is a mean method for Raster* objects. Therefore, you don't really need calc:

mean(s, na.rm=TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top