我有3个不等大小的数据框,我想根据它们的列标签合并在一起(按行)。
a = matrix(c(1,2,3,4,5,6),nrow=2,ncol=3)
b = matrix(c(1,3,4,5,6,7,8,9),nrow=2,ncol=4)
c = matrix(c(2,4,4,5,6,7),nrow=2,ncol=3)
a = data.frame(a)
b = data.frame(b)
c = data.frame(c)
colnames(a) <- c('Apples','Pears','Oranges')
colnames(b) <- c('Apples','Oranges','Peaches','Pears')
colnames(c) <- c('Apples','Pears','Peaches')
所以我在一个6行×4列的合并矩阵之后,所有Apple,Pear,Orange和Peach数据都在同一列中。
我该怎么做?
答案 0 :(得分:1)
这是你想要的吗?
library(plyr)
rbind.fill(a, b, c)
# Apples Pears Oranges Peaches
# 1 1 3 5 NA
# 2 2 4 6 NA
# 3 1 8 4 6
# 4 3 9 5 7
# 5 2 4 NA 6
# 6 4 5 NA 7
答案 1 :(得分:1)
Reduce(function(...) merge(..., all=TRUE), list(a,b,c))
# Apples Pears Peaches Oranges
# 1 1 3 NA 5
# 2 1 8 6 4
# 3 2 4 6 NA
# 4 2 4 NA 6
# 5 3 9 7 5
# 6 4 5 7 NA
答案 2 :(得分:1)
也使用plyr:
> library(plyr)
> join_all(list(a,b,c), type = "full")
Joining by: Apples, Pears, Oranges
Joining by: Apples, Pears, Peaches
Apples Pears Oranges Peaches
1 1 3 5 NA
2 2 4 6 NA
3 1 8 4 6
4 3 9 5 7
5 2 4 NA 6
6 4 5 NA 7