title: Calculating the mean across raster layers
body: <p>I am trying to average my precipitation data, which is an object in the form of a raster brick (the object is called &quot;Prec&quot;). &quot;Prec&quot; 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 &quot;Prec&quot; looks like:</p>
  <pre><code>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 
  </code></pre>
  <p>I tried the following:</p>
  <pre><code>ncfname &lt;- &quot;MaxPrecIPSLIPSL-CM5B-LRrcp85.nc&quot;
  Prec &lt;- brick(ncfname,var=&quot;onedaymax&quot;)
  sm &lt;- 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
  </code></pre>
  <p>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?</p>
  <p>Any assistance would be greatly appreciated!</p>