[R-sig-Geo] Monthly loop in raster stack with daily data

Loïc Dutrieux loic.dutrieux at wur.nl
Thu Oct 29 09:42:13 CET 2015


Hi Thiago,

I think zApply should get you there (for each stack independently).

library(zoo)
library(raster)

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

fun <- function(x, na.rm) {
   sum(x > 25, na.rm)
}
zApply(s, by=as.yearmon, fun = fun)

Cheers,
Loïc

On 10/29/2015 08:46 AM, Thiago V. dos Santos wrote:
> Hi all,
>
> I am working with very large raster stacks. Each stack is a time-series climate forecast, where the layers are *daily* values of a given meteorological variable (say temperature).
>
> How can I loop through the *months* in the raster and count the number of *days* above a certain threshold?
>
>
> Please see the code below showing a raster with two years of daily data:
>
> #Create a rasterStack similar to my data - same dimensions and layer names
> r <- raster(ncol=360, nrow=180)
> s <- stack(lapply(1:730, function(x) setValues(r, runif(ncell(r),min=0,max=30))))
> idx <- seq(as.Date("2010/1/1"), by = "day", length.out = 730)
> s <- setZ(s, idx)
> s
>
> hot.days <- calc(s, function(x,na.rm) sum(x) > 25) # I need to do this for every month in the raster stack, counting the number of days where temperature is greater than 25.
>
> The final raster would have 24 layers (12 months x 2 years) with the count of days.
>
> Is this analysis possible to be done on a raster or should I convert the data to a different format?
> Thanks a lot,
>   -- Thiago V. dos Santos
>
> PhD student
> Land and Atmospheric Science
> University of Minnesota
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



More information about the R-sig-Geo mailing list