How to remove rows with conflicting combination of column values without looping?

Viewed 57

Hi I have the opposite issue of duplication. Suppose I have a dataframe as such,

df = data.frame ( x=c("a","a","b","b","c"), y=c("yes","no", "yes","yes","no"))
> df
  x   y
1 a yes
2 a  no
3 b yes
4 b yes
5 c  no

So what I want is to remove 'a' rows, the reason is because 'a' has both 'yes' and 'no'. The ideal output would be to retain all rows with 'b' and 'c', "c" is retain because it too also has no conflict since it only appear once.

  x   y
1 b yes
2 b yes
3 c  no

The only way I can think of doing this is to loop through each unique x and test the length of the unique vector from y. But I'm wondering if there is an easier/ more effecient way of doing this, perhaps with dplyr?

thanks in advance.

1 Answers

Do a group by 'x' and filter based on the number of distinct elements equal to 1

library(dplyr)
df %>%
     group_by(x) %>% 
     filter(n_distinct(y) == 1) %>%
     ungroup

-ouput

# A tibble: 3 x 2
  x     y    
  <chr> <chr>
1 b     yes  
2 b     yes  
3 c     no   

Or may use subset with table in base R

subset(df, x %in% names(which(table(unique(df)$x) == 1)))
  x   y
3 b yes
4 b yes
5 c  no
Related