Search code examples
rloopsraster

How can I compute operations with all raster data of a specific folder in R?


I'm new in R. I have a folder (foder1) with a series of raster data (Raster01.tif, Raster02.tif, ....., Raster69.tif). I would multiply each raster by a number (0.0001) and save the resulting data with the same name, but in a new folder (folder2). How can I do this process?


Solution

  • You should always show what you have tried --- and there are similar questions on this site that you could refer to. Workflows could be something along these lines:

    Get input files

    library(raster)
    f <- list.files("folder1", pattern="tif$", full.names=TRUE)
    

    If they have the same extent and resolution

    s <- stack(f)
    s <- calc(s, function(x) x * 0.0001, filename="folder2/output.tif")
    

    or perhaps

    s <- stack(f)
    s <- s * 0.0001 
    writeRaster(s, filename="folder2/out.tif")
    # or use bylayer=T 
    writeRaster(s, filename="folder2/out.tif", bylayer=TRUE)
    

    To process the files one by one

     fun <- function(f) {
         r <- raster(f)
         outf <- gsub("folder1", "folder2", f)         
         writeRaster(r * 0.0001, outf)
     }
    
     f <- list.files("folder1", pattern="tif$", full.names=TRUE)
     x <- lapply(f, fun)