rdataframecbind

cbind multiple data.frames in a list with unequal lengths


I want to cbind the data frames in a list without recycling the items of short lengths

library(data.table)
library(dplyr)
library(rlist)

# Create a list of data.tables with unequal lengths
dt1 <- data.table(B = letters[1:3])
dt2 <- data.table( D = LETTERS[1:2])
dt3 <- data.table(F = letters[4:7])

# Put them in a list
dt_list <- list(dt1, dt2, dt3)

# cbind them
dplyr::bind_cols(dt_list)
rlist::list.cbind(dt_list)

updated: expected output or something similar

     B    D F
1    a    A d
2    b    B e
3    c <NA> f
4 <NA> <NA> g

Solution

  • library(data.table)
    library(dplyr)
    library(rlist)
    
    # Create a list of data.tables with unequal lengths
    dt1 <- data.table(B = letters[1:3])
    dt2 <- data.table( D = LETTERS[1:2])
    dt3 <- data.table(F = letters[4:7])
    
    # Put them in a list
    dt_list <- list(dt1, dt2, dt3)
    
    # Get max length of dts, pad shorter dts with NAs, bind together
    maxLen_v <- max(sapply(dt_list, nrow))
    dt_list <- lapply(dt_list, function(x) rbind(x, rep(NA, (maxLen_v-nrow(x))), use.names=F))
    dt_out <- dplyr::bind_cols(dt_list)
    
    dt_out
            B      D      F
       <char> <char> <char>
    1:      a      A      d
    2:      b      B      e
    3:      c   <NA>      f
    4:   <NA>   <NA>      g