1

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)

Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21
sbac
  • 1,897
  • 1
  • 18
  • 31

3 Answers3

3

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
Duck
  • 39,058
  • 13
  • 42
  • 84
3

A base R option

df2[setdiff(names(df1),names(df2))]<-NA
df3 <- rbind(df1,df2)

giving

> df3
# 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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

We can use rbindlist from data.table

library(data.table)
rbindlist(list(df1, df2), fill = TRUE)

-output

#   a b  c
#1: 1 4  1
#2: 2 5  5
#3: 3 6  7
#4: 8 5 NA
#5: 9 6 NA
akrun
  • 874,273
  • 37
  • 540
  • 662