I am attempting to aggregate daily data (35 years) to monthly then calculate seasonal mean using the raster package in R (I know how to do it with CDO). Below is my code, which outputs 4 seasonal means for all years (140 layers). How can I loop to output only 4 layers ( for the 4 seasons)?. I appreciate your help.
dailydata <- brick ("dailyrain.nc")
dates <- seq(as.Date("1981-01-01"), as.Date("2015-12-31"), by="day")
months <- format(dates, "%Y-%m")
Aggregate2Monthly <- function(x) {
agg <- aggregate(x, by=list(months), sum)
return(agg$x)
}
mothlydata <- calc(dailydata, Aggregate2Monthly)
mondates <- seq(as.Date("1981-01-01"), as.Date("2015-12-31"), by="month")
years <- format(mondates, "%Y")
seasons.def=c(1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4)
years.seasons <- paste(years, seasons.def, sep="-")
nyears <- years[!duplicated(years)]
nseas <- seasons.def[!duplicated(seasons.def)]
Aggregate2Seasons <- function(x) {
agg <- aggregate(x, by=list(years.seasons), mean)
return(agg$x)
}
seasonsdata <- calc(mothlydata, Aggregate2Seasons)