Search code examples
rspatialterra

Obtaining mean of rasters


I want to get a mean chlorophyll a from the 3 .nc files below, and am wondering if using mosaic is the correct thing to do?

https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/AQUA_MODIS.20020101_20021231.L3m.YR.NSST.sst.4km.nc https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/AQUA_MODIS.20030101_20031231.L3m.YR.NSST.sst.4km.nc https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/AQUA_MODIS.20040101_20041231.L3m.YR.NSST.sst.4km.nc

library(terra)

#List of .nc files in directory
fls <- list.files("/folder/with/files", ".nc$", full.names = TRUE)

#list of rast objects
r_list <- lapply(fls, rast)

#create spatial raster collection
coll <- sprc(r_list)

#Get the mean values across all rasters
chla_m<-mosaic(coll, fun="mean")

Solution

  • You can use the following code

    library(terra)
    
    #List of .nc files in directory
    fls <- list.files("/folder/with/files", ".nc$", full.names = TRUE)
    
    #list to SpatRaster object conversion
    r_list <- rast(fls)
    
    #For global mean calculation i.e. single mean for the entire SpatRaster
    global(r_list, mean, na.rm=TRUE)
    
    #For local mean calculation i.e. pixel-wise mean calculation
    mean(r_list, na.rm=TRUE)