2014-04-25 44 views
0

我有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列所有在同一列的蘋果,梨,橙和桃數據合併後矩陣我。

我該怎麼做?

+0

複製 - http://stackoverflow.com/questions/1299871/how-to-join-data-frames-in-r-inner-外左右 –

回答

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
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 
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