-1

[Data structure][1]I have a series of raster files which correspond to species biomass distribution per year. I am trying to take the mean of the first 5 years per each species. So far I managed to do as the code below. what the code does is to make the mean for all the years of that species. Instead i want to have the mean for the first 5 years. In the figure you see that years go from 12 to 264 so essentially the mean should be from 12 to 60 per each species

Any idea, tips?

all_files <- list.files(files_path,full.names = TRUE,pattern = ".asc$")
species = gsub("-.*.asc","",gsub(".*mass-","",all_files))
files_stack <- stack(all_files)
means = stackApply(files_stack, indices=species, fun=mean)


  [1]: https://i.stack.imgur.com/s7LyK.png

1 Answers1

0

Since your code is not reproducable its a bit of guesswork. If your datasets are ordered in years, you can try to break them into chunks first.

all_files <- list.files(files_path,full.names = TRUE,pattern = ".asc$")

split(all_files, ceiling(seq_along(all_files)/5)) -> files_5

lapply(files_5, function(files){
    species = gsub("-.*.asc","",gsub(".*mass-","",files))
    files_stack <- stack(files)
    means = stackApply(files, indices=species, fun=mean)
    return(means)
}

Read also here

tlhenvironment
  • 319
  • 2
  • 10
  • thanks, indeed this code splits different ascii files into groups of 5 but then when i try to apply the code with the mean it gives me this error: `Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘nlayers’ for signature ‘"character"’` – Chiara Piro Feb 02 '21 at 13:02