开发者

Merge two data frames in R and find common values and non-matching values

I am 开发者_JAVA技巧trying to find a function to match two data frames of different lengths on one common column only, and create a different column which specifies if it found a match or not. So, for example, df1 is:

Name Position location
francesca A 75
cristina B 36

And df2 is:

location Country
75 UK
56 Austria

And I would like to match on "Location" and the output to be something like:

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

I have tried with the function match or with:

subset(df1, location %in% df2)

But it does not work.

Could you please help me figure out how to do this?


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 location as you specified). If there are no matches, zero will be returned, so you get:

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

One caution: if there are multiple matches in the second table, you'd want to use a different approach as this method only returns the first match. I assume these are unique because of the way you specified your question, so this should not be an issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜