Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on grouped variable

Tags:

r

dplyr

I have a dataframe:

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

I want to filter for those groups only which contain both activities Act1 and Act2. The following code returns zero values:

df %>% group_by(Group) %>% filter(Activity == 'Act1' & Activity == 'Act2')

If I use df %>% group_by(Group) %>% filter(Activity %in% c('Act1' , 'Act2') ), it also returns group A, which I don't need.

How can I get only those groups that necessarily contain both the activities?

like image 561
Dhiraj Avatar asked Feb 07 '26 04:02

Dhiraj


1 Answers

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
like image 122
Ronak Shah Avatar answered Feb 09 '26 07:02

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!