gpt4 book ai didi

r - 过滤多个范围的时间序列

转载 作者:行者123 更新时间:2023-12-05 09:25:52 25 4
gpt4 key购买 nike

<分区>

假设我有这个时间序列数据框:

         date value1
1 2021-10-12 1.015
2 2021-10-13 NA
3 2021-10-14 NA
4 2021-10-15 1.015
5 2021-10-16 1.015
6 2021-10-17 1.015
7 2021-10-18 1.015
8 2021-10-19 1.015
9 2021-10-20 1.015
10 2021-10-21 1.015
11 2021-10-22 1.015
12 2021-10-23 1.015

df1 <- structure(list(date = structure(c(18912, 18913, 18914, 18915,
18916, 18917, 18918, 18919,
18920, 18921, 18922, 18923), class = "Date"),
value1 = c(1.015, NA, NA, 1.015, 1.015, 1.015, 1.015, 1.015,
1.015, 1.015, 1.015, 1.015)),
row.names = c(NA, -12L), class = "data.frame")

我想针对存储在数据框中的日期范围过滤此数据集,例如

Start      End
2021-10-12 2021-10-14
2021-10-16 2021-10-18
2021-10-22 2021-10-23

dtr <- structure(list(Start = structure(c(18912, 18916, 18922), class = "Date"),
End = structure(c(18914, 18918, 18923), class = "Date")),
class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L))

如果我想手动执行此操作,我可以编写一个 case_when 并使用 between 或类似的东西来过滤每个范围。但应该有一种方法可以遍历范围并使用矢量化解决方案进行过滤。

这是 case_when 方法:

df1 %>%
filter(case_when(
between(date, dtr$Start[1] & dtr$End[1]) ~ T,
between(date, dtr$Start[2] & dtr$End[2]) ~ T,
between(date, dtr$Start[3] & dtr$End[3]) ~ T,
TRUE ~ F
)


## date value1
## 1 2021-10-12 1.015
## 2 2021-10-13 NA
## 3 2021-10-14 NA
## 4 2021-10-16 1.015
## 5 2021-10-17 1.015
## 6 2021-10-18 1.015
## 7 2021-10-22 1.015
## 8 2021-10-23 1.015

如何矢量化过滤?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com