This builds on the previous raster calcuator example (http://rpubs.com/rural_gis/253031) by using a function to loop through a list of folders and add together the raster files within each folder using the sum function on a raster stack object.
#import required libraries
library(raster)
library(rgdal)
#list of folders containing the raster files
#in this example the folders are named after years
years <- c("2006", "2007", "2008", "2009" , "2010", "2011", "2012", "2013", "2014", "2015")
#initiate function (passing years/folders argument)
batch_rastSum <- function(years){
#loop through the different folders
for (i in 1:length(years)) {
#get a list of the input rasters in each folder
#pattern = "*.tif$" filters for main raster files only and skips any associated files (e.g. world files)
grids <- list.files(paste0("./Data/Reclass/", years[i], "/"), pattern = "*.tif$")
#create a raster stack from the input grids (in this example there are 12 tif files in each folder)
s <- raster::stack(paste0("./Data/Reclass/", years[i], "/", grids))
#run the sum function on the raster stack - i.e. add (non-cumulatively) the rasters together
r <- sum(s)
#write the output raster to file
r <- writeRaster(r, filename = paste0("./Data/YearSums/", "rc_Year_", years[i]), format="GTiff", overwrite=TRUE)
}
}
#run the function
batch_rastSum(years)