I have raster bricks of temperature and rainfall consisting of one layer for each month of the year. The raster brick looks like this:
> tmx
class : RasterBrick
dimensions : 3875, 8017, 31065875, 240 (nrow, ncol, ncell, nlayers)
resolution : 0.04490319, 0.04490319 (x, y)
extent : -180.0393, 179.9495, -90.04088, 83.95898 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
source : /scratch/bntjoa002/chelsa_cmip5_ts/tasmax/CHELSAcmip5ts_tasmax_ACCESS1-3_rcp8 5_2070-2089.nc
names : X2070.01.15, X2070.02.15, X2070.03.15, X2070.04.15, X2070.05.15, X2070.06.15, X2070.07.15, X2070.08.15, X2070.09.15, X2070.10.15, X2070.11.15, X2070.12.15, X2071.01.15 , X2071.02.15, X2071.03.15, ...
Date : 2070-01-15, 2089-12-15 (min, max)
varname : air_temperature
I have been using the following code to get the average monthly values for a specified period (e.g. resulting in 12 averaged layers, one for each month, over a X year period):
new_tmx <- subset(tmx, which(getZ(tmx) >= as.Date("2070-01-15") & getZ(tmx) <= as.Date("2089-12-15")))
indices <- format(as.Date(names(new_tmx), format = "X%Y.%m.%d"), format = "%m")
indices <- as.numeric(indices)
Monthlytmx<- stackApply(new_tmx, indices, fun = mean)
I do this separately for the maximum temperature, minimum temperature, and precipitation bricks.
What I need now is to do the same process, but instead to output one raster layer for each year consisting of the averaged values for one-year periods (i.e. for 2070, 2071, 2072...). I've only done very simple loops in R, and I'm not sure how to deal with the time/date function in this example?
rts
package that has functions that do exactly what you are asking (ie.,apply.monthly
). The package is specifically designed for raster time series analysis.