合并和匹配长度不等的数据帧

时间:2016-05-27 19:07:00

标签: r

我有DF1DF2

DF1
A    B
rs1  1
rs2  2
rs3  3

DF2
a    b
rs1  4
rs2  5
rs3  6
rs1  7
rs2  8
rs3  9

我想得到这样的输出

DF3
a_m    b   B_m
rs1    4   1
rs2    5   2
rs3    6   3
rs1    7   1
rs2    8   2
rs3    9   3

我正在尝试使用merge all=T(正如以前的帖子中所建议的那样),但它没有成功。

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

DF1
    A B
1 rs1 1
2 rs2 2
3 rs3 3
DF2
    a b
1 rs1 4
2 rs2 5
3 rs3 6
4 rs1 7
5 rs2 8
6 rs3 9
DF3 <- merge(DF1, DF2, by.x = "A", by.y = "a", all = T)
DF3
    A B b
1 rs1 1 4
2 rs1 1 7
3 rs2 2 5
4 rs2 2 8
5 rs3 3 6
6 rs3 3 9

答案 1 :(得分:0)

我们可以使用full_join

中的dplyr
library(dplyr)
full_join(DF2,DF1, by = c("a" = "A")) %>%
               setNames(., c("a_m", "b", "B_m"))
#  a_m b B_m
#1 rs1 4   1
#2 rs2 5   2
#3 rs3 6   3
#4 rs1 7   1
#5 rs2 8   2
#6 rs3 9   3