checking if two dataframes have the same values at the same row and column in R

Viewed 459

I have these two dataframes

x = c(2,4,2,4,4,6)
y = c("hi", "xyz" ,"xyz" ,"xyz" ,"xyz" ,"xyz")
z = c(2,4,5,5,5,5)
dfa = data.frame(X = x, Y = y, Z = z)
dfa

   X  Y      Z
1  2  "hi"   2
2  4  "xyz"  4
3  2  "xyz"  5
4  4  "xyz"  5
5  4  "xyz"  5
6  6  "xyz"  5

And another one with same rows and columns

x = c(2,7,8,2,4,6)
y = c("hi", "234" ,"xyz" ,"25" ,"xyz" ,"dfs")
z = c(20,4,5,3,1,5)
dfb = data.frame(X = x, Y = y, Z = z)
dfb

   X  Y      Z
1  2  "hi"   20
2  7  "234"  4
3  8  "xyz"  5
4  2  "25"   3
5  4  "xyz"  1
6  6  "dfs"  5

I want to get the number of times for each column that the value in dfa is the same as dfb

So for this example the output would be

    X   Y   Z
1   2   3   3

Kindly let me know how to proceed with this. Thank you very much

2 Answers

You can use mapply/Map :

mapply(function(x, y) sum(x== y), dfa, dfb)

Or similarly map2_dbl in purrr if you prefer tidyverse

purrr::map2_dbl(dfa, dfb, ~sum(.x == .y))

This is assuming that the columns in both the dataframes are in the same order, if they are not rearrange one dataframe based on another.

dfa <- dfa[names(dfb)]

We can use Map from base R

Map(function(x, y) sum(x == y, na.rm = TRUE), dfa, dfb)
Related