3

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)  
Fredrick
  • 37
  • 6
  • Possible duplicate of [Aggregate Daily Data to Month/Year intervals](https://stackoverflow.com/questions/6052631/aggregate-daily-data-to-month-year-intervals) – ClimateUnboxed Jun 08 '18 at 05:50

1 Answers1

3

You want to aggregate by a combination of year and month.

months <- format(dates, "%Y-%m")

Grouping months (as per your comment):

groups <- function(x) {
    d <- as.POSIXlt(x)

    ans <- character(length(x))
    ans[d$mon %in%  0:1] <- "JF"
    ans[d$mon %in%  2:4] <- "MAM"
    ans[d$mon %in%  5:8] <- "JJAS"
    ans[d$mon %in% 9:11] <- "OND"
    ans
}

Now use groups(dates) as the grouping variable. Check:

data.frame(dates, groups(dates))
##            dates groups.dates.
## 1     1981-01-01            JF
## 2     1981-01-02            JF
## 3     1981-01-03            JF
## 4     1981-01-04            JF
## 5     1981-01-05            JF
## 6     1981-01-06            JF
Enrico Schumann
  • 1,278
  • 7
  • 8
  • it works, would you have a suggestion for calculating seasonal mean of JF, MAM, JJAS, and OND from there? – Fredrick Jun 07 '18 at 12:56
  • but that will give daily means in the seasons instead of monthly means of the season?or am missing a point?.. – Fredrick Jun 08 '18 at 13:42
  • I have edited the code, I started with the monthly data to aggregate seasonal means, but I can only output 140 layers..how can I summarize 4 layers?.. – Fredrick Jun 09 '18 at 09:05
  • If you use `groups(dates)`, you don't need the first step: you can directly map the dates to `JF` and so on. – Enrico Schumann Jun 12 '18 at 09:46