2014-09-05 75 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