Simon Harmel
Simon Harmel

Reputation: 1489

subset based on two condition from grouped dataframe

In my data, I'm trying to subset unique study values where reporting is both subscale and composite.

In this data, the desired output will be the rows of study==1. I have tried the following with no success. Is there any fix?

library(tidyverse)
m="
study  reporting
1      subscale
1      composite
2      subscale
2      subscale
3      composite"

data <- read.table(text = m, h=T)

data %>% group_by(study) %>% 
  filter(reporting=="composite"&reporting=="subscale") # Doesn't return anything

Upvotes: 0

Views: 42

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You may try -

library(dplyr)

data %>% 
  group_by(study) %>% 
  filter(all(c('composite', 'subscale') %in% reporting)) %>%
  ungroup()

#  study reporting
#  <int> <chr>    
#1     1 subscale 
#2     1 composite

Upvotes: 1

Related Questions