Search code examples
rloopsfor-loopraster

How to exlude a raster from a loop


I have several raster files which I am passing a Gaussian filter and then I aggregate them based on a coarse resolution raster called ntl. I created this for loop but I don't know how to exclude the ntl raster from the loop. I have tried something like this, or this, and other thing but I am guessing I am doing something wrong because I get all sort of error depending on what I am trying. Here is the code:

wd = "path/"

ntl = rast(paste0(wd, "ntl.tif"))

v <- vect(paste0(wd, "lc.shp"))

doStuff <- function(file){
  
  pic = rast(file)
  
  for (i in seq(from = 0.3, to = 3, by = 0.1)) {
    
    print(i)
    
    gf <- focalMat(pic, i * res(ntl), "Gauss")
    r_gf <- focal(pic, w = gf, na.rm = TRUE)
    
    r_gf = exact_resample(r_gf, ntl, fun = 'mean', coverage_area = FALSE)
    
    r_gf <- mask(r_gf, v)
    ext(r_gf) <- ext(ntl)
    
    (stringedi = gsub("\\.", "", toString(format(i, nsmall = 2))))
    
    writeRaster(r_gf, 
                paste0("path/", 
                       basename(fs::path_ext_remove(file)),
                       stringedi, ".tif"), 
                overwrite=TRUE)
  }
  
}

list.files(wd, pattern = "tif$", full.names = TRUE) |>
  purrr::walk(doStuff)

Solution

  • You can either separate ntl.tif from your other .tif files so that list.files() doesn't see it, or a simple approach is to add an if statement that checks file in your function, i.e.

    doStuff <- function(file){
      if (file != file.path(wd, "ntl.tif")) {
        pic = rast(file)
      
        for (i in seq(from = 0.3, to = 3, by = 0.1)) {
          
          print(i)
          
          gf <- focalMat(pic, i * res(ntl), "Gauss")
          r_gf <- focal(pic, w = gf, na.rm = TRUE)
          
          r_gf = exact_resample(r_gf, ntl, fun = 'mean', coverage_area = FALSE)
          
          r_gf <- mask(r_gf, v)
          ext(r_gf) <- ext(ntl)
          
          (stringedi = gsub("\\.", "", toString(format(i, nsmall = 2))))
          
          writeRaster(r_gf, 
                      paste0("path/", 
                            basename(fs::path_ext_remove(file)),
                            stringedi, ".tif"), 
                      overwrite=TRUE)
        }
      }
    }
    

    Edit:

    Since you are experiencing an error exactly at the ntl.tif file, and the above does not work for some reason, I would recommend removing it from the list.files call, so that ntl.tif is never walked over. One approach to doing this is:

    files <- list.files(wd, pattern = "tif$", full.names = TRUE)
    files <- files[-grepl("^ntl\\.tif$", files)]
    purrr::walk(files, doStuff)
    

    If that does not work, and you still receive the Error in map(): i In index: 5. Caused by error: ! [focal] not a meanigful window error, replace grepl with the index causing issues (in this case 5) and see if that continues.