2016-07-14 85 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)