Search code examples
rappendwrite.table

R: append table horizontally


I have two 'data frames' that I'd like to append into a single csv file. I know that one can use write. table to append them, but write.table appends them vertically. Is there a way that I can append them horizontally?

Edit: The two data sets are 7x2 (which is constant), and Sx7 where S is variable. S can be very large, potentially up to 1000 or more.

Edit2: I want them to be arranged as with the Sx7 first, followed by a column of space, then the 7x2. I don't want them to be transposed as S can be very large and I'd like to be able to read them in LibreOffice/Excel.


Solution

  • This is definitely a quick hack.

    Your problem with using cbind is that the dataframes aren't of the same size. A quick way to fix this is to make them all the same size, filling in the blank spaces with something, in my case below NAs. Then you can cbind all the dataframes and output them as one big dataframe to a file. This will give the appearance of them being added horizontally, of course with all the redundant fillers.

    #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]])
    }