Nix
Nix

Reputation: 149

Filter groups based on single condition with dplyr in R

I have two data frames. df1

    col1
 1  apples
 2 oranges
 3  apples
 4  banana

df2

   setID    col1
1      1  apples
2      1 oranges
3      1  apples
4      1  banana
5      2  apples
6      2  grapes
7      2 oranges
8      2  apples
9      3 oranges
10     3  grapes
11     3  banana
12     3  banana
13     4  apples
21     4  apples
31     4  banana
41     4 oranges

I used filter from dplyr package to narrow down df2 by df1$col1[1] and putting the result in tempdf

> tempdf <- df2 %>% filter(df1$col1[1] == df2$col1)
> tempdf
  setID   col1
1     1 apples
2     1 apples
3     2 apples
4     2 apples
5     4 apples
6     4 apples

Is there a way I can see all the elements that have the same setID as the matched "apples"? Like this

         setID    col1
    1      1  apples
    2      1 oranges
    3      1  apples
    4      1  banana
    5      2  apples
    6      2  grapes
    7      2 oranges
    8      2  apples
    13     4  apples
    21     4  apples
    31     4  banana
    41     4 oranges

Upvotes: 2

Views: 550

Answers (1)

Florian
Florian

Reputation: 25435

You could use any in your filter statement, to filter groups where any of the entries for df2$col1 match the first entry of df1$col1.


Data:

df1 = read.table(text="col1
1  apples
2 oranges
3  apples
4  banana",header=T,stringsAsFactors=F)

df2 = read.table(text="   setID    col1
1      1  apples
2      1 oranges
3      1  apples
4      1  banana
5      2  apples
6      2  grapes
7      2 oranges
8      2  apples
9      3 oranges
10     3  grapes
11     3  banana
12     3  banana
13     4  apples
21     4  apples
31     4  banana
41     4 oranges",header=T,stringsAsFactors=F)

Code:

library(dplyr)
df2 %>% group_by(setID) %>% filter(any(col1==df1$col1[1]))

Output:

# A tibble: 12 x 2
# Groups:   setID [3]
   setID    col1
   <int>   <chr>
 1     1  apples
 2     1 oranges
 3     1  apples
 4     1  banana
 5     2  apples
 6     2  grapes
 7     2 oranges
 8     2  apples
 9     4  apples
10     4  apples
11     4  banana
12     4 oranges

Hope this helps!

Upvotes: 2

Related Questions