【问题标题】:dplyr filter to get only the values that one of the groups takedplyr 过滤器仅获取其中一个组采用的值
【发布时间】:2019-06-20 08:43:54
【问题描述】:

我想filter 从我的 tibble 的任何组中获取行,其中一个变量与其中一个组的值匹配。

structure(list(type = c("A", "A", "A", "A", "B", "B", "B", "B", 
"B"), categ = c("apple", "pear", "apple", "banana", "pear", "kiwi", 
"apple", "banana", "mango")), .Names = c("type", "categ"), row.names = c(NA, 
-9L), class = c("tbl_df", "tbl", "data.frame"))

#  type  categ 
#  <chr> <chr> 
#  A     apple 
#  A     pear  
#  A     apple 
#  A     banana
#  B     pear  
#  B     kiwi  
#  B     apple 
#  B     banana
#  B     mango 

我想从任何组中获取行,其中categ 是categ 在组 A 中为type 采用的值之一

基本上我想这样做:

df %>% 
  filter(categ %in% pull(filter(df, type == 'A'), categ))


#  type  categ 
#  <chr> <chr> 
#  A     apple 
#  A     pear  
#  A     apple 
#  A     banana
#  B     pear  
#  B     apple 
#  B     banana

这是一种丑陋的方法,我很确定有更好的方法,但我找不到。

感谢您的帮助,抱歉英语不好。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    一种可能是:

    df %>% 
     filter(categ %in% categ[type == "A"])
    
      type  categ 
      <chr> <chr> 
    1 A     apple 
    2 A     pear  
    3 A     apple 
    4 A     banana
    5 B     pear  
    6 B     apple 
    7 B     banana
    

    【讨论】:

      【解决方案2】:

      我们也可以使用slice

      library(dplyr)
      df %>% 
        slice(match(categ, categ[type == "A"]))
      # A tibble: 7 x 2
      #  type  categ 
      #  <chr> <chr> 
      #1 A     apple 
      #2 A     pear  
      #3 A     apple 
      #4 A     banana
      #5 A     pear  
      #6 A     apple 
      #7 A     banana
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 2020-09-16
        • 1970-01-01
        相关资源
        最近更新 更多