Search code examples
rexcelmerger-xlsxvba

How to export unequal length variables from R to an excel sheet?


I have two data frames in R as follows.

Team1 = c("a","b")
Grade1 = c(90,85)
DB1 = data.frame(Team1, Grade1)

Team2 = c("a","x","b")
Grade2 = c(79,92,85)
DB2 = data.frame(Team2, Grade2)

I want these four variables to be exported to a single excel sheet where the four columns should be 'Team1','Grade1', 'Team2' and 'Grade2'.

I used to export data frames to excel sheets using write.xlsx() function but the problem here is, variables are not equal in lengths. Same happens when I try to cbind() variables and export to excel.

Is there any way that I can export these four variables to an excel sheet without worrying about their lengths?


Solution

  • One option is cbind.fill to column bind the two datasets and it will fill the additional rows with NA

    library(rowr)
    DB12 <- cbind.fill(DB1, DB2, fill = NA)
    DB12
    #   Team1 Grade1 Team2 Grade2
    #1     a     90     a     79
    #2     b     85     x     92
    #3  <NA>   <NA>     b     85