Reputation: 1166
I'm trying to establish windows containing counts of days with the condition "T_mean between 18-23 and rh>=70%" by 5-days intervals since an specifyc time backwards (day 24-sep-14, in blue)
The desirebly column is 5day_int, that I calculated by hand.
My tries include dplyr::lag
but without success so far...
Any help would be really helpuful!
data:
tibble::tribble(
~date, ~t_mean, ~rh,
"15-sep-14", 20, 65,
"16-sep-14", 19, 68,
"17-sep-14", 21, 68,
"18-sep-14", 20, 76,
"19-sep-14", 18, 68,
"20-sep-14", 19, 78,
"21-sep-14", 17, 82,
"22-sep-14", 20, 54,
"23-sep-14", 21, 57,
"24-sep-14", 20, 75
)
Upvotes: 1
Views: 163
Reputation: 30474
Using zoo
and dplyr
one possible solution:
library(dplyr)
library(zoo)
df %>%
mutate(condition = ifelse(rh >= 70 & between(t_mean, 18, 23), 1, 0),
fiveday_int = rollapplyr(condition, width = 5, FUN = sum, partial = TRUE))
# A tibble: 10 x 5
date t_mean rh condition fiveday_int
<chr> <dbl> <dbl> <dbl> <dbl>
1 15-sep-14 20 65 0 0
2 16-sep-14 19 68 0 0
3 17-sep-14 21 68 0 0
4 18-sep-14 20 76 1 1
5 19-sep-14 18 68 0 1
6 20-sep-14 19 78 1 2
7 21-sep-14 17 82 0 2
8 22-sep-14 20 54 0 2
9 23-sep-14 21 57 0 1
10 24-sep-14 20 75 1 2
Data:
df <- tibble::tribble(
~date, ~t_mean, ~rh,
"15-sep-14", 20, 65,
"16-sep-14", 19, 68,
"17-sep-14", 21, 68,
"18-sep-14", 20, 76,
"19-sep-14", 18, 68,
"20-sep-14", 19, 78,
"21-sep-14", 17, 82,
"22-sep-14", 20, 54,
"23-sep-14", 21, 57,
"24-sep-14", 20, 75
)
Upvotes: 1