2014-09-05 77 views
-3

我有兩個'數據框',我想追加到一個單一的CSV文件。我知道可以使用寫入。表來追加它們,但write.table將它們垂直追加。有沒有一種方法可以水平追加它們?R:水平追加表格

編輯:兩個數據集是7x2(這是常數)和Sx7其中S是可變的。 S可能非常大,可能高達1000或更多。

編輯2:我想讓它們按照Sx7先排列,然後是一列空格,然後是7x2。我不希望它們被換位,因爲S可能非常大,我希望能夠在LibreOffice/Excel中讀取它們。

+1

請參閱'cbind'和'rbind'。 – zx8754 2014-09-05 19:37:06

+0

data.frames大小不同。 – Plinth 2014-09-05 19:45:01

+0

@Plinth嘗試從'plyr'合併''或'join' – akrun 2014-09-05 19:47:25

回答

1

這絕對是一個快速入侵。

您使用cbind的問題是數據幀的大小不一樣。解決這個問題的一個快速方法是使它們的大小相同,用一些東西填充空格,在我的情況下是NAs。然後,您可以將所有數據框綁定並將其作爲一個大數據框輸出到文件中。這將使它們的外觀水平添加,當然還有所有冗餘填充。

#create a list of the dataframes 
dfList<-list(df1, df2) 
#find the max rows 
maxRows<-max(sapply(dfList, nrow)) 

#define a function that makes all dataframes "cbind-able" 

equalRows<-function(df, numRows){ 
    numColumns<-ncol(df) 
    targetRows<-numRows-nrow(df) 
    toAppend<-as.data.frame(matrix(rep(NA, numColumns*targetRows), nrow=targetRows, ncol=numColumns)) 
    colnames(toAppend)<-colnames(df) 
    rbind(df, toAppend) 
} 

#create our new cbind-able dataframes 
newdfList<-lapply(dfList, function(df){ 

      if(nrow(df)==maxRows){ 
       df 
      }else{ 
       equalRows(df, maxRows) 
      } 
     }) 

#put them all in one for output 
dfResult<-newdfList[[1]] 
for(i in 2:length(newdfList)){ 
    dfResult<-cbind(dfResult, newdfList[[i]]) 
} 
+0

謝謝。有點笨重,但至少可以工作! – Plinth 2014-09-05 20:52:40

+0

@Plinth我相信有更好的方法來做到這一點,這可能不會很好地擴展,而且絕對笨重!但希望這是一個小問題的快速解決方案。如果這是你爲大量數據做的事情,我會追求其他途徑 – DMT 2014-09-05 21:23:25