Q:

How to filter by the elements of a Cartesian product of columns in R with dplyr?

I have a data.frame where
df = data.frame(a = c(1,1,1,2,2,2),b = c(1,2,1,2,1,2), c = c(1,2,3,4,5,6))

I want to keep the rows that match a key. For example,
key = data.frame(a = c(1,2), b = c(1,2))

In this case I want remove rows not containing (a = 1 and b = 1) or ( a = 2 and b = 2). In general the values of the a and b pairs are not the same value and there could be more matching columns than just two. The important part is keeping only the rows that are in the key. The resulting data.frame should look like
df_result = data.frame(a = c(1,1,2,2), b = c(1,1,2,2), c = c(1,3,4,6))

I can only come up with an inelegant approach with loops and if functions and is not as generalized as I need (stated above).
nomatch = numeric(0)
for(i in 1:nrow(df)){
   if((df$a[i] != key$a[1] | df$b[i] != key$b[1]) & (df$a[i] != key$a[2] | df$b[i] != key$b[2]))
       nomatch = c(nomatch,i)
}

df_result2 = df[-nomatch,]

I would prefer to be able to do this in dplyr.

A:

This is an inner join of df and key
library(dplyr)

df %>% 
  inner_join(key)

#   a b c
# 1 1 1 1
# 2 1 1 3
# 3 2 2 4
# 4 2 2 6

