Search code examples
raverager-raster

Calculating the mean across raster layers


I am trying to average my precipitation data, which is an object in the form of a raster brick (the object is called "Prec"). "Prec" has 95 layers. However, the idea would be to average just the first 20 layers. For example, the first grid cell of the first layer would be averaged with the first grid cell of the second layer, and then the third layer, the fourth layer.....all the way to the 20th layer. This would be done for all grid cells (8192 cells per layer) for each layer. This is what object "Prec" looks like:

Prec

class       : RasterBrick 
dimensions  : 64, 128, 8192, 95  (nrow, ncol, ncell, nlayers)
resolution  : 2.8125, 2.789327  (x, y)
extent      : -181.4062, 178.5938, -89.25846, 89.25846  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
data source : C:/Users/Rain/Documents/My documents/All netCDF files/netcdffiles/MaxPrecIPSLIPSL- 
CM5B-LRrcp85.nc 
names       : X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, ... 
z-value     : 1, 95 (min, max)
varname     : onedaymax 

I tried the following:

ncfname <- "MaxPrecIPSLIPSL-CM5B-LRrcp85.nc"
Prec <- brick(ncfname,var="onedaymax")
sm <- mean(Prec[1:20], na.rm=TRUE) #Attempting to calculate the mean by isolating first 20 layers 
(example: Grid cell #1 of layer #1 is averaged with Grid cell #1 of layer #2....all the way to layer 
#20 

sm
[1] 20.8997

While this goes through, it only returns one value, as opposed to a single layer of 8192 average values from the 20 layers. Why would this be happening?

Any assistance would be greatly appreciated!


Solution

  • Here is a minimal, self-contained, reproducible example:

    library(raster)
    b <- brick(system.file("external/rlogo.grd", package="raster"))
    

    To get the mean for all (in this case 3) layers

    m <- mean(b)
    

    To get the mean for the first two layers

    m <- mean(b[[1:2]])
    

    Note that the double brackets [[ are used to subset layers. The single brackets [ are to extract values. Thus b[1:2] returns the values for the first two cells. See ?raster::subset