I wanted to calculate the seasonal average value for each year and not for the entire period. I defined my seasons as follows: DJF (December-February), MAM (March-May), JJA (June-August) and SON (September-November).
Inspired by the solution of the question of Fredrick, I created a index "groups" which represents the seasons then I applied the command "stackApply" but this one calculates the average seasonal value for the all of period. I explain, the final layer obtained contains only 4 raster but for my case I wanted to calculate "the seasonal average value for each year, therefore it is necessary to have 4 rasters for each year and in total the rasterstack should have 136 rasters.
Below my code
Thanks for your help
library(raster)
set.seed(123)
r <- raster(ncol=10, nrow=10)
r_brick <- brick(sapply(1:408, function(i) setValues(r, rnorm(ncell(r), i, 3))))
dim(r_brick)
dates <- seq(as.Date("1982-01-01"), as.Date("2015-12-31"), by="month")
months <- format(dates, "%Y-%m")
groups <- function(x) {
d <- as.POSIXlt(x)
ans <- character(length(x))
ans[d$mon %in% c(11,0:1)] <- "DJF"
ans[d$mon %in% 2:4] <- "MAM"
ans[d$mon %in% 5:7] <- "JJA"
ans[d$mon %in% 8:10] <- "SON"
ans
}
data.frame(dates, groups(dates))
r_brick.s <- stackApply(r_brick, indices=groups(dates), fun=mean,na.rm=TRUE)
nlayers(r_brick.s)