如何在R中执行两个数据帧的内部联接和外部联接?
内部联接仅返回左侧表在右表中具有匹配键的行,外部联接返回两个表中的所有行,左侧联接返回在右表中具有匹配键的记录。这可以通过使用合并功能来完成。
示例
内部联接
> df1 = data.frame(CustomerId = c(1:5), Product = c(rep("Biscuit", 3), rep("Cream", 2)))
> df1
CustomerId Product
1 1 Biscuit
2 2 Biscuit
3 3 Biscuit
4 4 Cream
5 5 Cream
> df2 = data.frame(CustomerId = c(2, 5, 6), City = c(rep("Chicago", 2),
rep("NewYorkCity", 1)))
> df2
CustomerId City
1 2 Chicago
2 5 Chicago
3 6 NewYorkCity内部联接
> merge(x = df1, y = df2) CustomerId Product City 1 2 Biscuit Chicago 2 5 Cream Chicago
外连接
> merge(x = df1, y = df2, by = "CustomerId", all = TRUE) CustomerId Product City 1 1 Biscuit <NA> 2 2 Biscuit Chicago 3 3 Biscuit <NA> 4 4 Cream <NA> 5 5 Cream Chicago 6 6 <NA> NewYorkCity
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短