title: R: Matching rows by two columns
body: <p>I am currently trying to figure out a vectorized way to match by two values in the same row. I have the following two simplified data frames: </p>
  
  <pre><code># Dataframe 1: Displaying all my observations
  df1 &lt;- data.frame(c(1, 2, 3, 4, 5, 6, 7, 8),
                    c("A", "B", "C", "D", "A", "B", "A", "C"), 
                    c("B", "E", "D", "A", "C", "A", "D", "A"))
  colnames(df1) &lt;- c("ID", "Number1", "Number2")
  
  &gt; df1
    ID Number1 Number2
  1  1       A       B
  2  2       B       E
  3  3       C       D
  4  4       D       A
  5  5       A       C
  6  6       B       A
  7  7       A       D
  8  8       C       A
  
  # Dataframe 2: Matrix of observations I am interested in
  df2 &lt;- matrix(c("A", "B",
                  "D", "A",
                  "C", "B",
                  "E", "D"),
                ncol = 2,
                byrow = TRUE)
  
  &gt; df2
       [,1] [,2]
  [1,] "A"  "B" 
  [2,] "D"  "A" 
  [3,] "C"  "B" 
  [4,] "E"  "D" 
  </code></pre>
  
  <p>What I am trying to accomplish is to create a new column in df1 that states TRUE only if the exact combination is present in df2 (for example ID = 1 is equivalent to the first row in df2 because both of them consist of A and B). Additionally, if there is a shortcut, I would also like the status to be TRUE if the numbers are reversed, i.e. df1$Number1 matches df2[i,2] and df1$Number2 matches df2[i,1] (for example for ID = 7, the combination in df1 is A,D and in df2, the combination is D,A --> TRUE).</p>
  
  <p>My desired output looks like this:</p>
  
  <pre><code>&gt; df1
    ID Number1 Number2 Status
  1  1       A       B   TRUE
  2  2       B       E  FALSE
  3  3       C       D  FALSE
  4  4       D       A   TRUE
  5  5       A       C  FALSE
  6  6       B       A  TRUE
  7  7       A       D  TRUE
  8  8       C       A  FALSE
  </code></pre>
  
  <p>All I have gotten so far is this: </p>
  
  <pre><code>for (i in 1:nrow(df1)) {
    for (j in 1:nrow(df2)) {
      Status &lt;- ifelse(df1$Number1[i] %in% df2[j,1] &amp;&amp; 
                       df1$Number2[i] %in% df2[j,2], TRUE, FALSE)
      StatusComb[i,j] &lt;- Status
    }
    df1$Status[i] &lt;- ifelse(any(StatusComb[i,]) == TRUE, TRUE, FALSE)
  }
  </code></pre>
  
  <p>It is really inefficient (you can clearly tell I am new to R) and does not look very nice either. I would appreciate any help!</p>