如何匹配R中具有相同主键的两个表中的数据 [英] How to match data from two tables with same primary key in R

查看:152
本文介绍了如何匹配R中具有相同主键的两个表中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,其中包含有关人的数据:

I have two tables with data about people:

df1 <- data.frame(id=c(113,202,377,288,359),
                  name=c("Alex","Silvia","Peter","Jack","Jonny"))

哪个为我提供了

   id   name
1 113   Alex
2 202 Silvia
3 377  Peter
4 288   Jack
5 359  Jonny

还有第二张表,其中包含了他们的家庭成员的名字:

And I have a second table containing the names of their family members:

df2 <- data.frame(id=c(113,113,113,202,202,359,359,359,359),
                 family.members=c("Ross","Jefferson","Max","Jo","Michael","Jimmy","Rex","Bill","Larry"))

这为我提供了:

> df2
   id family.members
1 113           Ross
2 113      Jefferson
3 113            Max
4 202             Jo
5 202        Michael
6 359          Jimmy
7 359            Rex
8 359           Bill
9 359          Larry

现在,我想用一个额外的列来扩展表1,该列包含每个人的家庭成员的总和:

Now I want to extend table 1 with an additional column containing the sum of family members for each person:

    id   name no.family.memebers
1  113   Alex                  3
2  202 Silvia                  2
3  377  Peter                  0
4  288   Jack                  0
5  359  Jonny                  4

在R中创建第三个表的最佳方法是什么?

What is the best way to create the third table in R?

推荐答案

使用 dplyr

library(dplyr)
df1 <- df1 %>% left_join((
    df2 %>% group_by(id) %>%
    summarize(no.family.members = n())
    )
)






使用 dplyr > = 0.3.0.2可以将其重写为


With dplyr >= 0.3.0.2 it could be rewritten as

df3 <- df1 %>% left_join(df2 %>% count(id))

这篇关于如何匹配R中具有相同主键的两个表中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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