I have a dataset in time series (an observation per day). What I would like to do is find the number of days until an observation is above zero for each day in the dataset.
A sample of the dataset looks like this:
Date Runoff
01/01/1980 0
02/01/1980 0
03/01/1980 0
04/01/1980 0
05/01/1980 4.5
06/01/1980 2
07/01/1980 0
08/01/1980 0
09/01/1980 0
10/01/1980 0
11/01/1980 0
12/01/1980 0
13/01/1980 1.2
14/01/1980 0
15/01/1980 0
16/01/1980 0
17/01/1980 0
18/01/1980 0.8
And what I would like to get to is this:
Date Runoff No_Days
01/01/1980 0 4
02/01/1980 0 3
03/01/1980 0 2
04/01/1980 0 1
05/01/1980 4.5 0
06/01/1980 2 0
07/01/1980 0 6
08/01/1980 0 5
09/01/1980 0 4
10/01/1980 0 3
11/01/1980 0 2
12/01/1980 0 1
13/01/1980 1.2 0
14/01/1980 0 4
15/01/1980 0 3
16/01/1980 0 2
17/01/1980 0 1
18/01/1980 0.8 0
So as you can see if there is runoff on a particular date then there are 0 days until runoff, if there is a runoff event the next day then there is 1 day until runoff etc.
I've been using R for a while and this is the first time I haven't been able to find a solution hence this is my first R related question on here so please go easy on me!
If I've missed anything don't hesitate to let it be known.
Thank you,
J
I was also thinking of
rle
andseq_len
:Here's a more R way. I am using
rle
and a bit of hack