Skip to content
Prev 23655 / 29559 Next

How to perform cross-year date operations on rasters?

Hi Thiago,

Building on Michael's answer and your example, I think the following should work. The tricky part is to build the right by= argument for zApply().
You can see zApply as a wrapper of aggregate.zoo() for temporal raster bricks, and you're more likely to find answers for aggregate.zoo than for zApply when searching the internet.
This is where I found the answer: https://stat.ethz.ch/pipermail/r-help/2008-August/171366.html

Cheers,
Lo?c Dutrieux

library(raster)
library(zoo)
library(lubridate)

# Create a rasterStack similar to cmip5 - same dimensions and layer names
r <- raster(ncol=180, nrow=90)
s <- stack(lapply(1:1825, function(x) setValues(r, runif(ncell(r)))))
idx <- seq(as.Date("2010/1/1"), by = "day", length.out = 1825)
s <- setZ(s, idx)

# Separate layers with months of interest
ldates <- format(getZ(s), "%m") %in% c("10", "11", "12", "01")
s2 <- subset(s, which(ldates))

# Apply function
s3 <- zApply(s2, by=year(as.yearmon(getZ(s2)) - 1/12), fun = sum))
On 11/05/2015 07:17 PM, Thiago V. dos Santos wrote: