I have a set of data with precipitation totals (Precip) for every day. I collected data at multiple pools. I need to calculate the number of days it has been since the last time it raied >12mm. If it rained over 12mm that day then it get a ‘0’.
## creates example dataframe
Pool <- c("A","A","A","A","A","A","A","A","A","A",
"B","B","B","B","B","B","B","B","B","B")
DATE <- as.Date(c("2005-01-01","2005-01-02","2005-01-03","2005-01-04","2005-01-05",
"2005-01-06","2005-01-07","2005-01-08","2005-01-09","2005-01-10",
"2005-01-01","2005-01-02","2005-01-03","2005-01-04","2005-01-05",
"2005-01-06","2005-01-07","2005-01-08","2005-01-09","2005-01-10"))
Precip <- c(0,0,3,18,4,3,13,8,3,0,13,0,3,13,0,3,10,8,13,0))
df <- data.frame(Pool, DATE, Precip)
I need the following dataframe:
Pool DATE Precip Days_since12
1 A 2005-01-01 0 NA
2 A 2005-01-02 0 NA
3 A 2005-01-03 3 NA
4 A 2005-01-04 18 NA
5 A 2005-01-05 4 1
6 A 2005-01-06 3 2
7 A 2005-01-07 13 0
8 A 2005-01-08 8 1
9 A 2005-01-09 3 2
10 A 2005-01-10 0 3
11 B 2005-01-01 13 0
12 B 2005-01-02 0 1
13 B 2005-01-03 3 2
14 B 2005-01-04 13 0
15 B 2005-01-05 0 1
16 B 2005-01-06 3 2
17 B 2005-01-07 10 3
18 B 2005-01-08 8 4
19 B 2005-01-09 13 0
20 B 2005-01-10 0 1
I can easily add a column to indicate if the precip was over 12 or not:
df2 <- df %>%
group_by(Pool) %>%
mutate(pre12=ifelse(Precip>12,1,0))
But I am then not sure how to calculate the number of days between the DATE and the previous date when pre12==1