【问题标题】:Duplicate elimination by group and condition not working按组重复消除和条件不起作用
【发布时间】:2022-07-30 00:37:08
【问题描述】:

我有 col2 包含值 A、B、C 或 D,而 col3 有新旧日期。

我可以使用group_byslice_head 仅过滤 col2 中的 A 来隔离 col1 中找到的以下重复项,但是,

我要做的是根据以下过滤器删除重复项,但是(仅在“A”中删除基于 col1 和 col2 的重复项),并保留表示来自 col3 的最近日期的行 slice(n = 1) 并且仍然将所有 A、B、C、D 保留在最终输出中 - 让 B、C、D 不因重复等而受到影响。相反,我只能在输出中保留 col2 的 A,而我会丢失 B、C、D 行。

df %>% 
  group_by(col1, col3) %>% 
  filter(n() > 1 & col2 == 'A') %>% 
  arrange(desc(col1, col3)) %>% 
  slice_head(n = 1) %>% 
  ungroup

原始集

col1  col2 col3 (date)
11    A    older date
11    A    newer date
12    B    only 1 date
13    C    only 1 date
14    D    only 1 date
22    A    newer date
22    A    older date

当前输出:

col1  col2  col3
11    A     Newer
22    A     Newer

期望:

col1   col2 col3
11     A    Newer date
12     B    Only 1 date
13     C    Only 1 date
14     D    Only 1 date
22     A    Newer date

【问题讨论】:

  • 你能在过滤器中添加|n() == 1 & col2 != "A"

标签: r dplyr


【解决方案1】:

分组似乎只基于'col1',然后我们需要在filter中添加另一个条件

df %>% group_by(col1) %>% filter(n() == 1|col2 == "A" & n() > 1) %>% arrange(desc(col3), .by_grorup = TRUE) %>% slice_head(n = 1) %>% ungroup

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2019-06-18
    • 2018-10-27
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2018-09-13
    相关资源
    最近更新 更多