Merge two data frames in R and find the common values ​​and the inappropriate values

I am trying to find a function to match two data frames of different lengths for only one common column and create another column that indicates whether it found a match or not. So for example df1:

Name Position location francesca A 75 cristina B 36 

And df2:

 location Country 75 UK 56 Austria 

And I would like to match the "Location", and the result is something like:

 Name Position Location Match francesca A 75 1 cristina B 36 0 

I tried with match function or with:

 subset(df1, location %in% df2) 

But that will not work.

Could you help me figure out how to do this?

+4
source share
1 answer

Try:

 df1$match <- match(df1$location, df2$location, nomatch=0) 

This will add a column to df1 indicating which row in df2 matches it (considering only the location you specify). If there are no matches, zero is returned, so you get:

 > df1 Name Position location match 1 francesca A 75 1 2 cristina B 36 0 

One warning: if there are several matches in the second table, you need to use a different approach, since this method returns only the first match. I assume they are unique due to the way you asked your question, so this should not be a problem.

+8
source

All Articles