Search code examples
rbind

How to bind tibbles by row with different number of columns in R


I want to bind df1 with df2 by row, keeping the same column name, to obtain df3.

library(tidyverse)

  df1 <- tibble(a = c(1, 2, 3),
                b = c(4, 5, 6),
                c = c(1, 5, 7))
  
  df2 <- tibble(a = c(8, 9),
                b = c(5, 6))
  
  # how to bind these tibbles by row to get
  
  df3 <- tibble(a = c(1, 2, 3, 8, 9),
                b = c(4, 5, 6, 5, 6),
                c = c(1, 5, 7, NA, NA))

Created on 2020-10-30 by the reprex package (v0.3.0)


Solution

  • Try this using bind_rows() from dplyr. Updated credit to @AbdessabourMtk:

    df3 <- dplyr::bind_rows(df1,df2)
    

    Output:

    # A tibble: 5 x 3
          a     b     c
      <dbl> <dbl> <dbl>
    1     1     4     1
    2     2     5     5
    3     3     6     7
    4     8     5    NA
    5     9     6    NA