Reputation: 19
I have a rainfall time series and would like to know the accumulated amount of rainfall that spanned 5 days or more.
My data are daily observations as shown below.
Date | Prec |
---|---|
1983-01-01 | 1.12 |
1983-01-02 | 1.08 |
1983-01-03 | 1.11 |
1983-01-04 | 2.00 |
1983-01-05 | 1.44 |
1983-01-06 | 3.12 |
1983-01-07 | 0.12 |
1983-01-08 | 0.52 |
1983-01-09 | 1.62 |
1983-01-10 | 0.12 |
1983-01-11 | 1.33 |
1983-01-12 | 1.14 |
1983-01-13 | 1.16 |
1983-01-14 | 1.00 |
1983-01-15 | 5.12 |
1983-01-16 | 6.12 |
I've already got the sum of days by setting a range of days (5 consecutive days), but there is the possibility of having a longer sequence of days that meet my condition.
prec <- transform(prec, extreme =+(Prec < 2))
r <- rle(prec$extreme)
r$values[r$values == 1] <- r$lengths[r$values == 1]
prec <- transform(prec, n=unlist(Map(rep, r$values,
r$lengths)))
and the result I hope is this:
I've already got the sum of days by setting a range of days (5 consecutive days), but there is the possibility of having a longer sequence of days that meet my condition. And I want there to be columns of total consecutive days (Prec < 2), cumulative total of those consecutive days, start date and end date of the sequence.
Thanks in advance!
Upvotes: 0
Views: 346
Reputation: 16978
You could use dplyr
:
library(dplyr)
data %>%
group_by(grp = cumsum(Prec > 2)) %>%
filter(Prec <= 2) %>%
summarise(start_date = min(Date),
end_date = max(Date),
rain_acc = sum(Prec),
days_con = n()) %>%
select(-grp)
returns
# A tibble: 2 x 4
start_date end_date rain_acc days_con
<date> <date> <dbl> <int>
1 1983-01-01 1983-01-05 6.75 5
2 1983-01-07 1983-01-14 7.01 8
structure(list(Date = structure(c(4748, 4749, 4750, 4751, 4752,
4753, 4754, 4755, 4756, 4757, 4758, 4759, 4760, 4761, 4762, 4763
), class = "Date"), Prec = c(1.12, 1.08, 1.11, 2, 1.44, 3.12,
0.12, 0.52, 1.62, 0.12, 1.33, 1.14, 1.16, 1, 5.12, 6.12)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -16L), spec = structure(list(
cols = list(Date = structure(list(format = ""), class = c("collector_date",
"collector")), Prec = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
Upvotes: 1