0

I have 2 dataframes, i am trying to combine both the dataframes not only the ones with common names but also with different variable names and tell as NA if respective value not found.

I tried normal rbind but it asks for same column names.

Dataframes:

d1 <- data.frame(a=c('a1','a2','a3'), b = c("a51","a52","a53"), d = c(12,13,14))

d2 <- data.frame(a=c('a4','a5','a6'), g = c("a151","a152","a153"), k = c(122,123,124))

Expected Output:

   a    b  d    g   k
1 a1  a51 12 <NA>  NA
2 a2  a52 13 <NA>  NA
3 a3  a53 14 <NA>  NA
4 a4 <NA> NA a151 122
5 a5 <NA> NA a152 123
6 a6 <NA> NA a153 124
prog
  • 1,073
  • 5
  • 17

1 Answers1

1

Here is an option with bind_rows

library(dplyr)
bind_rows(d1, d2)
#  a    b  d    g   k
#1 a1  a51 12 <NA>  NA
#2 a2  a52 13 <NA>  NA
#3 a3  a53 14 <NA>  NA
#4 a4 <NA> NA a151 122
#5 a5 <NA> NA a152 123
#6 a6 <NA> NA a153 124

Or using rbindlist

library(data.table)
rbindlist(list(d1, d2))
akrun
  • 874,273
  • 37
  • 540
  • 662