2016-07-14 59 views
0

所以我有这个大的数据框的列表,其中一些有匹配的列和其他人没有。我想用匹配的列来合并那些没有匹配列的合并列表(基于变量Year,Country)。但是,我不想手动查看所有的数据框来查看哪些数据框具有匹配的列,哪些没有。Rbind和合并在R

现在我在想,情况就会沿着这个线路:

myfiles = list.files(pattern="*.dta") 
dflist <- lapply(myfiles, read.dta13) 

for (i in 1:length(dflist)){ 

    if colnames match 
    put them in list and rbindlist. 
    else put them in another list and merge. 
}  

除了不知道如何R中做到这一点正好,我开始觉得这不会工作后,所有。

为了说明考虑6个dataframes:

Dataframe 1:       Dataframe 2: 

Country Sector Emp    Country Sector Emp 
Belg  A  35    NL  B  31 
Aus  B  12    CH  D  45 
Eng  E  18    RU  D  12 

Dataframe 3:      Dataframe 4: 
Country Flow PE    Country Flow PE 
NL  6  13     ... ... ... 
HU  4  11     ... ... 
LU  3  21     ... 

Dataframe 5:    dataframe 6: 

Country Year Exp   Country Year Imp 
GER  02 44   BE  00 34 
GER  03 34   BE  01 23 
GER  04 21   BE  02 41 

在这种情况下,我会想rbind(数据帧1,dataframe2)和rbind(数据帧3,数据帧4),我想合并数据帧5和6,根据变量国家和年份。所以我的输出将是几个rbinded/merged数据帧..

+0

我认为合并(所有= TRUE)将rbind(虽然比较慢),所以它可能工作只是把它们合并在一起。有关如何做到这一点,http://stackoverflow.com/questions/8091303/simultaneously-merge-multiple-data-frames-in-a-list – Aaron

回答

0

Rbind将失败,如果列不相同。建议您可以使用dplyr软件包中的mergeleft_join

也许这将工作:do.call(left_join, dflist)