Search code examples
rtidyversetidytable

tidyverse: Comparing each row of a data.frame with a single row from another data.frame


I want to compare each row of df1 with a single row of df2 in tidy way. Any hint please.

df1 <-
  structure(
    list(
        Q1 = c("a", "a")
      , Q2 = c("b", "a")
      , Q3 = c("a", "a")
      , Q4 = c("b", "a")
      )
    , class = "data.frame"
    , row.names = c(NA, -2L)
    )

df2 <-
  structure(
    list(
        Q1 = "a"
      , Q2 = "a"
      , Q3 = "b"
      , Q4 = "c"
      )
    , class = "data.frame"
    , row.names = c(NA, -1L)
    )

library(tidyverse)


sum(df1[1, ] == df2)
[1] 1
sum(df1[2, ] == df2)
[1] 2

Solution

  • In Base

    apply(df1,1, function(x) sum(x == df2))
    
    [1] 1 2