Sum rasters folder by folder

I have a series of species distribution rasters, separated in different folders according to the observation date. I have 1 folder for each day of 2024, named like %Y%m%d, e.g. 20240101.

I want to do 2 simple operations, using {raster}:

  1. Merge all files in a given folder, producing a raster of the sum of distributions of all species observed in a given day.

  2. After having the “daily sum” rasters, I want to sum them cumulatively. For example: 1st raster = day 1; 2nd raster = day 1 + day 2, …

I know I can do the first operation by creating a long script similar to this:

       library(raster)
        files <- list.files("D:/Fantasy Birding/Ranges/Rasters/Observados/20240101", pattern="*.tif$", full.names=TRUE)
        rs <- stack(files)
        soma <- calc(rs, sum)
        writeRaster(soma, "D:/Fantasy Birding/Ranges/Rasters/Observados por dia/diario20240101.tif")
    
    
     files <- list.files("D:/Fantasy Birding/Ranges/Rasters/Observados/20240102", pattern="*.tif$", full.names=TRUE)
        rs <- stack(files)
        soma <- calc(rs, sum)
        writeRaster(soma, "D:/Fantasy Birding/Ranges/Rasters/Observados por dia/diario20240102.tif")

However, preparing such script is quite time consuming. What would be the best way to automate this process?

To achieve this without having to do it step by step, use:

  1. a helper function with lapply() to sum rasters for each day and write them to the “Observados por dia” directory
  2. a for() loop to cumulatively sum the diario rasters

Some regular expression (regex) magic will help with the file naming. You didn’t specify where to write the cumulative results, or what to name them. In this reprex, they are written to a new folder called “cumulative” and each file has the mmdd of the most recent date appended to the start date e.g. cumu20240101_0102.tif, cumu20240101_0103.tif etc.

Step 1: Sum rasters by day

library(raster)

# Create list of tif files from every subdirectory in Observados
files <- list.files("D:/Fantasy Birding/Ranges/Rasters/Observados/",
                    pattern="*.tif$", 
                    full.names = TRUE,
                    recursive = TRUE)

# Create a list of tif files grouped by subdirectory
sub_files <- split(files, sub(".*/([^/]+)/.*", "\1", files))

# Helper function to process each group in sub_files
r_sum <- function(files) {
  
  output_path <- paste0("D:/Fantasy Birding/Ranges/Rasters/Observados por dia/diario", 
                        sub(".*/([^/]+)/.*", "\1", files[1]), ".tif")
  
  writeRaster(calc(stack(files), sum), output_path, overwrite = TRUE)
  
}

# Sum each sub_files group and write result to Observados por dia directory
invisible(do.call(c, lapply(sub_files, r_sum)))

Step 2: Cumulatively sum rasters

# Create list of summed tif files from previous step
files <- list.files("D:/Fantasy Birding/Ranges/Rasters/Observados por dia/",
                    pattern="*.tif$", 
                    full.names = TRUE)

# Create directory for cumulative sum results
dir.create(file.path("D:/Fantasy Birding/Ranges/Rasters/cumulative/"), showWarnings = FALSE)

# Create raster object for start of loop (if you run the loop again,
# be sure to run this every time also)
x <- raster(files[1])

# Cumulatively sum diario rasters
for(i in 2:length(files)) {
  
  output_path <- paste0("D:/Fantasy Birding/Ranges/Rasters/cumulative/cumu20240101_", 
                        sub(".*([0-9]{4})\.tif$", "\1", files[i]), ".tif")
  
  x <- calc(stack(x, files[i]), sum)
  writeRaster(x, output_path, overwrite = TRUE)
  
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật