Filtering on grouped variable

后端 未结 1 1123
你的背包
你的背包 2021-01-20 17:17

I have a dataframe:

df <- data.frame(
          Group=c(\'A\',\'A\',\'A\',\'B\',\'B\',\'B\'),
          Activity = c(\'Act1\',\'Act4\', \'Act3\',\'Act1\',         


        
相关标签:
1条回答
  • 2021-01-20 17:56

    You need to wrap it any

    library(dplyr)
    df %>% 
      group_by(Group) %>% 
      filter(any(Activity == 'Act1')  & any(Activity == 'Act2'))
    
    # Group Activity
    #  <fct> <fct>   
    #1 B     Act1    
    #2 B     Act2    
    #3 B     Act3 
    

    Using the same logic in base R option ave

    df[as.logical(ave(df$Activity, df$Group, 
                  FUN = function(x) any(x == 'Act1')  & any(x == 'Act2'))), ]
    

    You can get the same result using all

    df %>% 
      group_by(Group) %>% 
      filter(all(c("Act1", "Act2") %in% Activity))
    

    and similar with ave

    df[as.logical(ave(df$Activity, df$Group, 
               FUN = function(x) all(c("Act1", "Act2") %in% x))),]
    
    
    # Group Activity
    #4     B     Act1
    #5     B     Act2
    #6     B     Act3
    
    0 讨论(0)
提交回复
热议问题