在R中找到两个数据帧之间的公共ID [英] find the common ids between two data frames in R

查看:87
本文介绍了在R中找到两个数据帧之间的公共ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下数据帧:

id1<-c(1,2,3,4,5)
spent<-c(10,20,30,40,50)
id2<-c(1,3,4)
x<-c(1,2,2)
df1<-data.frame(id1,spent)
df2<-data.frame(id2,x)

我需要在 df1 中找到ID,这些ID也存在于 df2 中,并导出所有信息到新的数据框(例如 df3 )。在此基础上 df3 应该如下所示:

I need to find the ids in df1 which also exist in df2 and export all their information to a new data frame (let's say df3). on this basis df3 should look as follow:

   id1     spent
   1         10
   3         30
   4         40

如果能您可以为我解决这个问题。

I would be thankful if you could help me with this problem.

推荐答案

使用合并参见?合并获取有关 by.x by.y 参数

Use merge see ?merge for get information about by.x and by.y arguments

merge(df1, df2, by.x="id1", by.y="id2")[,-3] # this is the desired output you showed
  id1 spent
1   1    10
2   3    30
3   4    40

merge(df1, df2, by.x="id1", by.y="id2") # this is with "all their information"
  id1 spent x
1   1    10 1
2   3    30 2
3   4    40 2

这篇关于在R中找到两个数据帧之间的公共ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆