Search code examples
rrasterr-modis

What are the ways for the faster processing of raster stack


I have been trying to calculate the monthly means of 8day MODIS data and it is taking very long to calculate the mean. Is there a faster way to do this. I am using the following code to do it in R:

library(doParallel)
library(foreach)
library(raster)
# Set the number of cores to use for parallel processing
ncores <- parallel::detectCores() - 1  # Use all available cores except one
registerDoParallel(cores = ncores)

m<-stack()

foreach (month_name = month.name) %dopar% {
  print(month_name)
  # Subset layers corresponding to the current month
  month_layers <- s[[which(months(getZ(s)) == month_name)]]
  print(month_layers)
  # Calculate mean for the month (exclude NA values)
  month_mean <- mean(month_layers, na.rm = TRUE)
  print(month_mean)
  # Store the monthly mean in the list with the month name as the list element name
  m<-stack(m,month_mean)
}

Solution

  • I would do

    library(terra)
    x <- rast(files)
    m <- tapp(x, "months", mean, cores=ncores)