0

I have a dataframe containing the columns "Date", "Snow_depth" and "hydro_year". The "Snow_depth"-column contains values from 0-150. To identify the number and length of continuous snowdays, meaning days with "Snow-depth"-values greater than 0, I´m trying to add a column which contains ascending numbers starting from the first "Snow-depth"-value greater than 0 and ending with the next 0 of the "Snow-depth"-column + Zeros/NAs for each row with a "Snow-depth"-value of 0. As soon as I got this I would then count the number of "2"-values of that new column (since 2 days is the minimum for a snow-period) to detect the number of periods and also filter the hightest and lowest values for each hydroyear to detect the max- and min-length.

Does anyone know how to create that column I described?

What I need shpuld look like this:

Snow_depth: 0, 0, 5, 7, 8, 4, 0, 0, 6, 5, 8, 9, 5, 6, 0, 8, 6...

New_column: 0, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2...

Any help would be much much appreciated! Thanks!

a_zrhch
  • 17
  • 4
  • See [Create counter within consecutive runs of certain values](https://stackoverflow.com/questions/5012516/create-counter-within-consecutive-runs-of-certain-values) and Linked therein. For next time, please learn how to create an easily reproducible example. Cheers. – Henrik Jul 06 '21 at 20:27
  • E.g. `ave(x!=0, cumsum(x==0), FUN = cumsum)` – Henrik Jul 06 '21 at 20:36

1 Answers1

0

You can use purrr:accumulate() here. First create a logical vector with snow_depth !=0, than call accumulate with if_else.

library(purrr)
library(dplyr)

df%>%mutate(consecutive_days=accumulate(snow_depth!=0, ~if_else(.y!=0, .x+1, 0)))

   snow_depth new_column consecutive_days
1           0          0                0
2           0          0                0
3           5          1                1
4           7          2                2
5           8          3                3
6           4          4                4
7           0          0                0
8           0          0                0
9           6          1                1
10          5          2                2
11          8          3                3
12          9          4                4
13          5          5                5
14          6          6                6
15          0          0                0
16          8          1                1
17          6          2                2

data

df<-data.frame(snow_depth=c(0, 0, 5, 7, 8, 4, 0, 0, 6, 5, 8, 9, 5, 6, 0, 8, 6),
           new_column=c(0, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2))
GuedesBF
  • 8,409
  • 5
  • 19
  • 37