title: how to add average rasters within for-loop that creates the rasters? R
body: <p>I have several directories with 700+ binary encoded rasters that i take average the output rasters per directory. however, i currently create the rasters 1 by 1 in a for loop, then load newly created rasters back into R to take the sum to obtain the monthly rainfall total. </p>
  
  <p>However, since I dont need the individual rasters, only the average raster, I have a hunch that I could do this all w/in 1 loop and not save the rasters but just the output average raster, but I am coming up short in how to program this in R. </p>
  
  <pre><code>setwd("~/Desktop/CMORPH/Levant-Clip/200001")
  
  dir.output &lt;- '~/Desktop/CMORPH/Levant-Clip/200001' ### change as needed to give output location
  path &lt;- list.files("~/Desktop/CMORPH/MonthlyCMORPH/200001",pattern="*.bz2", full.names=T, recursive=T)
  
  for (i in 1:length(path)) {
    files = bzfile(path[i], "rb")
    data &lt;- readBin(files,what="double",endian = "little", n = 4948*1649, size=4) #Mode of the vector to be read
    data[data == -999] &lt;- NA #covert missing data from -999(CMORPH notation) to NAs
    y&lt;-matrix((data=data), ncol=1649, nrow=4948)
    r &lt;- raster(y)
    e &lt;- extent(-180, 180, -90, 83.6236) ### choose the extent based on the netcdf file info 
    tr &lt;- t(r) #transpose 
    re &lt;- setExtent(tr,extent(e)) ### set the extent to the raster
    ry &lt;- flip(re, direction = 'y')
    projection(ry) &lt;- "+proj=longlat +datum=WGS84 +ellps=WGS84"
    C_Lev &lt;- crop(ry, Levant) ### Clip to Levant
    M_C_Lev&lt;-mask(C_Lev, Levant)
    writeRaster(M_C_Lev, paste(dir.output, basename(path[i]), sep = ''), format = 'GTiff', overwrite = T) ###the basename allows the file to be named the same as the original
  }
  # 
  raspath &lt;- list.files ('~/Desktop/CMORPH/Levant-Clip/200001',pattern="*.tif",     full.names=T, recursive=T)
  rasstk &lt;- stack(raspath)
  sum200001&lt;-sum(rasstk)
  writeRaster(avg200001, paste(dir.output, basename(path[i]), sep = ''), format = 'GTiff', overwrite = T) ###the basename allows the file to be named the same as the original
  </code></pre>
  
  <p>currently, this code takes about 75 mins to execute, and I have about 120 more directories to go, and am looking for faster solutions.</p>
  
  <p>thank you for all and any comments and input. best, evan</p>