根据通用列在R中组合两个数据框 [英] combine two dataframes in R based on common columns
本文介绍了根据通用列在R中组合两个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须合并两个看起来像这样的数据帧 我想将数据框之间的通用列合并在一起. 两个数据帧中的行将完全不同.
I have to combine two data-frames which look like this I want to take the common column among the data-frames and join them together. Rows in two data-frames will be completely different.
a b c
row1 1 0 1
row2 1 0 1
另一个数据框
d a c f
row3 1 0 1 1
row4 1 1 0 0
我希望最终的数据集看起来像这样
I want the final dataset to look like this
a c
row1 1 1
row2 1 1
row3 0 1
row4 1 0
这是来自两个数据帧的输出
Here is the dput from two dataframes
dput(x1)
structure(list(d = c(1L, 1L), a = 0:1, c = c(1L, 0L), f = c(1L,
0L)), .Names = c("d", "a", "c", "f"), row.names = c("row3", "row4"
), class = "data.frame")
dput(x2)
structure(list(a = c(1L, 1L), b = c(0L, 0L), c = c(1L, 1L)), .Names = c("a",
"b", "c"), row.names = c("row1", "row2"), class = "data.frame")
推荐答案
您可以获取通用名称,然后使用行绑定:
You could get the common names and then use row bind:
common <- intersect(names(x1), names(x2))
rbind(x1[,common], x2[,common])
a c
row3 0 1
row4 1 0
row1 1 1
row2 1 1
匹配您的预期输出
rbind(x2[,common], x1[,common])
a c
row1 1 1
row2 1 1
row3 0 1
row4 1 0
这篇关于根据通用列在R中组合两个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文