Monica Heddneck
Monica Heddneck

Reputation: 3115

Comparing two similar dataframes and finding different values between them

This is a seemingly basic question, I apologize in advance if this is a duplicate question. I looked around and didn't see anything.

I have two dataframes full of strings. I'd like to see if they are EXACT duplicates of each other.

If they are not, I'd like to determine which values are different.

Specifically, given this dataframe:

| x | y |
|---|---|
| a | e |
| b | f |
| c | g |
| d | h |

and this dataframe:

| x | y |
|---|---|
| a | l |
| b | m |
| j | g |
| k | h |

I would like to generate this result (a df full of non-matching values):

| x | y |
|---|---|
|   | l |
|   | m |
| j |   |
| k |   |

This question is super close to what I'm thinking, but it wants to find full rows that are the same, not values.

1) I don't think I have any choice other than to iterate across each value, one by one, testing via string matching. I know this df1 %in% df2 will test for rows. But how do I test for each element?

2) After I can test each element, I'd need to construct a dataframe to store the non-matches. I'm not sure how to do it.

It seems like a simple idea, but breaking it down, the implementation actually seems rather complex. Any bumps in the right direction would be greatly appreciated.

My data:

df1 <- data.frame(
  x = c('a', 'b', 'c', 'd'),
  y = c('e', 'f', 'g', 'h')
)


df2 <- data.frame(
  x = c('a', 'b', 'j', 'k'),
  y = c('l', 'm', 'g', 'h')
)

Upvotes: 3

Views: 411

Answers (1)

Haboryme
Haboryme

Reputation: 4761

You could do:

df2[mapply(function(x,y)   x%in%y ,df1,df2)]<-NA
     x    y
1 <NA>    l
2 <NA>    m
3    j <NA>
4    k <NA>

This affects df2 directly, better have a copy of it.

Explanation:
mapply() is used to have the %in% applied between the first column of df1 and df2, and then the second and so on if there were more.
This gives:

> mapply(function(x,y)   x%in%y,df1,df2)
         x     y
[1,]  TRUE FALSE
[2,]  TRUE FALSE
[3,] FALSE  TRUE
[4,] FALSE  TRUE

TRUE are the values that matched, these are the want we want to change into NA's.

Upvotes: 3

Related Questions