代码之家  ›  专栏  ›  技术社区  ›  fugu

如果通过筛选,则保留同一组中的行

  •  1
  • fugu  · 技术社区  · 7 年前

     df <- data.frame(sample = c("R1", "R2", "R2", "R2", "R3", "R3"), event = c(1, 10, 10, 20, 3, 3), name = c('foo', 'bar', 'baz', 'baz', 'foo', 'baz'))
    

    我想选择按分组的行 sample event name == 'baz' .

    所需输出:

      sample event name
    2     R2    10  bar # another row in same sample, event group has name == 'baz' 
    3     R2    10  baz
    4     R2    20  baz
    5     R3     3  foo # another row with same sample, event group has name == 'baz' 
    6     R3     3  baz
    

      df %>% 
        group_by(sample, event) %>% 
        filter(name == 'baz')
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   erocoar    7 年前

    你可以简单地使用 any()

    df %>% 
      group_by(sample, event) %>%
      filter(any(name == "baz"))
    
    # A tibble: 5 x 3
    # Groups:   sample, event [3]
      sample event name 
      <fct>  <dbl> <fct>
    1 R2        10 bar  
    2 R2        10 baz  
    3 R2        20 baz  
    4 R3         3 foo  
    5 R3         3 baz