rrasterterra

Save each layer as individual file with ifel in terra


I have a large raster stack composed of dozens of layers. I would like to save each layer directly to disk with ifel however the filename function within ifel creates a single output file. The help file for ifel directs towards writeRaster for additional arguments but in writeRaster, each layer is saved individually which is what I would like.

r <- rast(nrows=5, ncols=5, xmin=0, xmax=1, ymin=0, ymax=1)
values(r) <- c(-10:0, NA, NA, NA, 0:10)

s<-r*1.2

r.stack<-c(r, s)
names(r.stack)<-c("r", "s")
t <- rast(nrows=5, ncols=5, xmin=0, xmax=1, ymin=0, ymax=1)

values(t) <- c(rep(1, 5), rep(2, 5), rep(3, 5), rep(2, 5), rep(3, 5))

x <- ifel(t==3, 5, r.stack,
          filename=paste("test",names(r.stack), ".tiff", sep=""))
#Warning message:
#[cover] only the first filename supplied is used

output: a single .tiff file with both layers

desired output: two .tiff files for each layer named with the layer name

writeRaster(x,filename=paste("test",names(r.stack), ".tiff", sep=""))

Solution

  • filename works differently inside ifel() as it can only write a single output file. In this instance, it is designed to save the modifications made to a single input object.

    On the other hand, writeRaster() accepts:

    a single filename, or as many filenames as nlyr(x) to write a file for each layer.

    To achieve your desired outcome:

    library(terra)
    
    # Create modified version of t SpatRaster
    x <- ifel(t == 3, 5, r.stack)
    
    # Write each layer in x to woring directory
    writeRaster(x, 
                filename = paste("test", names(r.stack), ".tiff", sep = ""),
                overwrite = TRUE)
    
    # List all tiff files starting with "test" in working directory
    list.files(pattern = "^test.*\\.tiff$")
    # [1] "testr.tiff" "tests.tiff"
    
    rast("testr.tiff")
    # class       : SpatRaster 
    # dimensions  : 5, 5, 1  (nrow, ncol, nlyr)
    # resolution  : 0.2, 0.2  (x, y)
    # extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
    # coord. ref. : lon/lat WGS 84 (EPSG:4326) 
    # source      : testr.tiff 
    # name        :   r 
    # min value   : -10 
    # max value   :   5 
    
    rast("tests.tiff")
    # class       : SpatRaster 
    # dimensions  : 5, 5, 1  (nrow, ncol, nlyr)
    # resolution  : 0.2, 0.2  (x, y)
    # extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
    # coord. ref. : lon/lat WGS 84 (EPSG:4326) 
    # source      : tests.tiff 
    # name        :   s 
    # min value   : -12 
    # max value   :   6