sfetan
sfetan

Reputation: 109

Extracting rows from a data frame depending on the combination of values in two colums

I got a data frame

a <- c('A','A','A','A','B','B','C','C')
b <- c(1,2,1,3,1,3,1,6)
c <- c('K','K','H','H','K','K','H','H')

frame <- data.frame(a,b,c)

> frame
  a b c
1 A 1 K
2 A 2 K
3 A 1 H
4 A 3 H
5 B 1 K
6 B 3 K
7 C 1 H
8 C 6 H

And now I want to extract data the following way: If the string in 'a' occurs in a row with 'K' AND in a row with 'H', the rows with a 'K' will be left out. In the end it should look like this:

> frame
  a b c
1 A 1 H
2 A 3 H
3 B 1 K
4 B 3 K
5 C 1 H
6 C 6 H

Maybe you got any ideas. Thank you!

Upvotes: 2

Views: 46

Answers (2)

akrun
akrun

Reputation: 887691

We could use a group by filter

library(dplyr)
frame %>%
    group_by(a) %>%
    filter(all(c('K', 'H') %in% c) & c != 'K'|n_distinct(c) == 1)
# A tibble: 6 x 3
# Groups:   a [3]
#  a         b c    
#  <fct> <dbl> <fct>
#1 A         1 H    
#2 A         3 H    
#3 B         1 K    
#4 B         3 K    
#5 C         1 H    
#6 C         6 H    

Upvotes: 1

GKi
GKi

Reputation: 39717

You can use intersect to find strings in a having H and K in column c and then extract those where column c holds a K.

frame[!(frame$a %in% intersect(frame$a[frame$c=="K"],
   frame$a[frame$c=="H"]) & frame$c=="K"),]
#  a b c
#3 A 1 H
#4 A 3 H
#5 B 1 K
#6 B 3 K
#7 C 1 H
#8 C 6 H

Upvotes: 3

Related Questions