按 r 中的时间间隔计算
count if by time interval in r
我正在尝试建立 windows 包含条件 "T_mean between 18-23 and rh>=70%" 的天数,自指定时间向后(24 年 9 月 24 日,蓝色)[=5 天间隔]
理想的列是 5day_int,这是我手工计算的。
我的尝试包括 dplyr::lag
但到目前为止没有成功...
任何帮助都会非常有帮助!
数据:
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
)
使用zoo
和dplyr
一种可能的解决方案:
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
数据:
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
)
我正在尝试建立 windows 包含条件 "T_mean between 18-23 and rh>=70%" 的天数,自指定时间向后(24 年 9 月 24 日,蓝色)[=5 天间隔]
理想的列是 5day_int,这是我手工计算的。
我的尝试包括 dplyr::lag
但到目前为止没有成功...
任何帮助都会非常有帮助!
数据:
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
)
使用zoo
和dplyr
一种可能的解决方案:
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
数据:
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
)