Search code examples
rnafillcbind

Bind different length data frames by columns from bottom


I am looking for options (preferably using base R) for binding different length data frames starting from bottom. The remaining/missing rows should be NAd out. Example:

set.seed(1212)
a = as.data.frame(rnorm(1, 0, 1))
b = as.data.frame(rnorm(4, 0, 1))
c = as.data.frame(rnorm(3, 0, 1))

Expected output:

  rnorm(1, 0, 1) rnorm(4, 0, 1) rnorm(3, 0, 1)
1 NA               1.8374224       NA
2 NA               0.3436815       0.03719874
3 NA              -1.3600955      -1.92311898
4 -0.6290858       0.5358145       0.41087971

Solution

  • First, assess the maximum length of the columns to bind.

    lenMax <- max(length(a[,1]), length(b[,1]), length(c[,1]))
    

    Then, use this length to fill columns of a new data.frame with NAs so they fit.

    data.frame(a = c(rep(NA, lenMax - length(a[,1])), a[,1]), 
               b = c(rep(NA, lenMax - length(b[,1])), b[,1]), 
               c = c(rep(NA, lenMax - length(c[,1])), c[,1]))
    
    #            a          b           c
    # 1         NA  1.8374224          NA
    # 2         NA  0.3436815  0.03719874
    # 3         NA -1.3600955 -1.92311898
    # 4 -0.6290858  0.5358145  0.41087971