# [R] Runs of at least 5 days with certain value in a rasterbrick in R

Adam Dragula @d@m@dr@gu|@1998 @end|ng |rom gm@||@com
Wed Jan 20 22:45:45 CET 2021

```Dear R users,

I am  working with a rasterbrick named X, which has got 6300 time layers.
Those 6300 time layers represent every winter day since 1.1.1950 till
31.12. I dropped all 29th of february so that I had 90 time layers for
every season. Values throughout the whole domain are between 0.5 and 1.5. I
successfully made a function, which creates a rasterlayer, which contains
amount of runs of at least 5 days with values greater than 1.0. So for
every grid point, I have got amount of events I am looking for. The
function is following:

ff<-function(x,na.rm=TRUE){
y<-x > 1
n<- ave(y,cumsum(y == 0), FUN = cumsum)
sum(n >= 5)
}

This works very well, however, there is a problem. After layer which
represents 28.2., 1.12., 2.12. and so on.. follows. It means, that event
starting 28.2. may be detected if the criterion is satisfied throughout the
first four days of following december. Of course I dont wanna detect such
events as those are two distinct seasons. So I tried something like this
(to somehow divide it into 70 seasons and calculate function ff for them):

indices<-rep(1:70,each=90)
XX<-stackApply(X,indices,fun=ff)

At first sight, this works and no error is written. However, results are
miscounted and there is too much events detected, for example 20 events are
detected in the first layer at maximum, which doesnt make any sense
(20x5=100, there is just 90 days per season). Other fact is, that this
works perfectly fine, if I dont divide the whole series and use the
criterion through original brick X without any indices.
I cant see where the problem is, so every help is deeply appreciated, maybe
another way could be more efficient.