r – 按日期和按条件分组

在 R 中,使用dplyr我想为每个组过滤大于一个日期。

下面给了我结果,但我想知道是否有更优雅的方法来获得同样的东西。是否可以在不使用的情况下进行过滤mutate

max_dates <- data.frame(col_1 = c('a', 'b', 'c'), max_date = c('2021-08-23', '2021-07-19', '2021-07-02'))


df <- data.frame(col_1 = c(rep('a', 10), rep('b', 10), rep('c', 10)),
                 date = rep(seq(as.Date('2021-07-01'), by = 'week', length.out = 10), 3))

desired_df <- df %>% 
  left_join(max_dates, by = 'col_1') %>% 
  mutate(greater_than = ifelse(date >= max_date, T, F)) %>% 
  filter(greater_than)

回答

你不需要 mutate 参数;将条件移动到过滤器参数...

library(dplyr)
df %>%
left_join(max_dates, by = 'col_1') %>%
filter(date >= max_date)
#>    col_1       date   max_date
#> 1      a 2021-08-26 2021-08-23
#> 2      a 2021-09-02 2021-08-23
#> 3      b 2021-07-22 2021-07-19
#> 4      b 2021-07-29 2021-07-19
#> 5      b 2021-08-05 2021-07-19
#> 6      b 2021-08-12 2021-07-19
#> 7      b 2021-08-19 2021-07-19
#> 8      b 2021-08-26 2021-07-19
#> 9      b 2021-09-02 2021-07-19
#> 10     c 2021-07-08 2021-07-02
#> 11     c 2021-07-15 2021-07-02
#> 12     c 2021-07-22 2021-07-02
#> 13     c 2021-07-29 2021-07-02
#> 14     c 2021-08-05 2021-07-02
#> 15     c 2021-08-12 2021-07-02
#> 16     c 2021-08-19 2021-07-02
#> 17     c 2021-08-26 2021-07-02
#> 18     c 2021-09-02 2021-07-02

由reprex 包( v2.0.0 )于 2021 年 8 月 31 日创建


以上是r – 按日期和按条件分组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>