In the context of a RUSLE erosion modelling I would like to calculate the sum of precipitation at the entry date of phenological phases.

Suppose I have 13 grids, one of which is the phenophase entry date PhenoDate with values from 1 to 356, the other 12 represent average daily shares of the annual precipitation sum for the individual months [dPrecJan,...,dPrecDec].

I would like to calculate the precipitation sum using a set of conditional statements:

If the phenophase begins in january, multiply the phenophase entry date with the january average daily precipitation, else if the phenophase begins in february, multiply [...]

I already tried to implement my conditional statements using the sum of products, where the condition returns either 0 or 1:

PrecSum <- ((PhenoDate<32) * PhenoDate * dPrecJan) + (
(PhenoDate>=32 & PhenoDate<60) * ((31*dPrecJan)+((PhenoDate-31) * dPrecFeb))) + (
(PhenoDate>=60 & PhenoDate<91) * ((31*dPrecJan)+(28*dPrecFeb)+(
(PhenoDate-59) * dPrecMar))) + (( [etc.]))

Actually not too complicated construction, but since I use very high-resolution raster layers, the calculation goes beyond my memory capacities.

I'm looking for a memory-efficient construction, which allows to set multiple conditional statements on my raster calculation.

  • How high is "very high resolution"? Assuming your code works then this is totally a question about lowering memory usage, and without a precise statement of usage we can't properly help.
    – Spacedman
    Aug 20 '19 at 21:44
  • every single sub-expression here (PhenoDate<32) implies memory usage, so I'd be trying a couple of those in isolation and see how it's handled, is the result in memory or backed to a (new) file. You might get the job done by saving several intermediate raster objects. The resolution per se is irrelevant, what matters is the number of pixels, e.g. dim(PhenoDate)
    – mdsumner
    Aug 20 '19 at 21:51
  • If the issue is about memory and not speed, you can split the rasters, do the computation part by part, save each part to a file and combine them at the end of the computation. It's a bit dirty but I think it makes the job
    – Chelmy88
    Aug 21 '19 at 8:25
  • Could you please share anyhow some of your rasters (or some clip) and your code ? Aug 26 '19 at 15:40

I solved the issue using a nested ifelse() construction:

    myform<-function(PhenoDate,dPrecJan,dPrecFeb,[...],dPrecDec) { ifelse (
    PhenoDate < 32, PhenoDate * dPrecJan, ifelse (
    PhenoDate>=32 & PhenoDate<60, 31 * dPrecJan + ((PhenoDate-31) * dPrecFeb), ifelse (
    PhenoDate>=60 & PhenoDate<91, 31 * dPrecJan+ 28 * dPrecFeb+((PhenoDate-59) * dPrecMar), ifelse (

I stacked the 13 grids using stack():


Then I used overlay()


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.