Search code examples
rrasterterra

How to overlay more than 2 files in r?


We can compute the mean of corresponding layers from 2 stacks like this.

library(raster)
s1 <- stack(system.file("external/rlogo.grd", package="raster")) 
s2 <- sqrt(s1)
m4 <- overlay(s1, s2, fun=function(x) mean(x, na.rm=TRUE))

I have several files in a folder:

 data<- list.files ("C:data\\", ".nc", full.names = TRUE)
 for (i in 1:length(data)){
     nn=stack(dff[i])
     res=nn[[1:8]]
     ...............}

How can I apply the overlay function to all res


Solution

  • It is easier to do this with "terra" (the replacement of "raster"),

    Example data

    library(terra)
    s1 <- rast(system.file("ex/logo.tif", package="terra"))   
    s2 <- sqrt(s1)
    

    Solutions to get the "parallel" mean with two SpatRasters:

    mean(s1, s2)
    
    #class       : SpatRaster 
    #dimensions  : 77, 101, 3  (nrow, ncol, nlyr)
    #resolution  : 1, 1  (x, y)
    #extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
    #coord. ref. : Cartesian (Meter) 
    #source(s)   : memory
    #names       :      red,    green,     blue 
    #min values  :   0.0000,   0.0000,   0.0000 
    #max values  : 135.4844, 135.4844, 135.4844 
    

    Or like this

    app(sds(s1, s2), mean)
    

    If you have many files (SpatRasters) you can do:

    f <- system.file("ex/logo.tif", package="terra")
    ff <- rep(f, 5)
    
    s <- sds(ff)
    app(s, mean)
    
    # or 
    x <- lapply(ff, rast)
    do.call(mean, x)
    
    # or
    x <- lapply(ff, rast)
    app(sds(x), mean)
    

    To subset each SpatRaster before the computations, you can do

    x <- lapply(ff, \(f) rast(f)[[1:2]])
    do.call(mean, x)
    

    Or (but this is currently broken)

    s <- sds(ff)
    s <- s[, 1:2,drop=FALSE]
    app(s, mean)
    

    You can, of course, also subset the output with [[1:2]]


    Note that to get the mean of all layers you could do this instead

    mean(c(s1, s2))
    # or
    app(c(s1, s2), mean)