我正在尝试计算多个开始日期和结束日期之间的时间序列中的值的平均值。
简单的设置:
time_series <- tibble(dates=seq.Date(from=ymd('20240101'), to=ymd('20241231'), 'day'),
value = runif(366,max=10))
target_dates <-tibble(id=c('A','B','C'),
start=ymd(c('20240104','20240504','20240704')),
end =ymd(c('20240201','20240524','20240924'))) %>%
mutate(ndays=as.integer(end-start))
我想计算每个 target_dates$start 和 target_dates$end 之间的 time_series$value 的平均值。
我无法弄清楚如何从两个单独的小标题中做到这一点。
我的第一个想法是这个(以及这次尝试的变体)。
target_dates %>%
group_by(start) %>%
summarise(avg = mean(time_series %>% slice(first(which(dates==start)):slice(last(which(dates==end)))) %>% select(values)))
但是,这不起作用。
这也出现在我的脑海中,但在 b/c 上不起作用,因为 Between 函数不适用于向量。我可以编写一个 for 循环,但这并不优雅。
time_series %>%
summarise(avg = mean(value[between(target_dates$start,target_dates$end)]))
计算 ndays 列是因为我尝试使用滑块库中的 slip_idx_double 但无法弄清楚如何将时间序列数据添加到以
开头的语句中time_series %>%
summarise(avg = slide_index_dbl(WHAT GOES HERE??,start,.after=ndays,mean))
我期望创建一个 tibble/数据框,其中计算 target_dates 开始日期和结束日期之间时间序列 time_series tibble 值列的平均值。
感谢帮助。
查看加入是否适用于您的数据
library(dplyr)
right_join(time_series, target_dates, join_by(between(dates, start, end))) %>%
summarize(Mean = mean(value), .by = c(id, start, end))
# A tibble: 3 × 4
id start end Mean
<chr> <date> <date> <dbl>
1 A 2024-01-04 2024-02-01 3.63
2 B 2024-05-04 2024-05-24 5.91
3 C 2024-07-04 2024-09-24 4.82