0

Can we combine rows of multiple dataframe with different columns. Example below

> asd1 <- data.frame(a = c("a","b"), b = c("fd", "fg"))
> asd1
  a  b
1 a fd
2 b fg

> asd2 <- data.frame(a = c("a","b"), e = c("fd", "fg"), c = c("gfd","asd"))
> asd2
  a  e   c
1 a fd gfd
2 b fg asd

Newdf <- rbind(asd1, asd2)
Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match

Right now there is an error since of different columns.

Expected output

newdf 
data    a    b    e    c  
asd1    a   fd    NA   NA
asd1    b   fg    NA   NA
asd2    a   NA    fd   gfd
asd2    b   NA    fg   asd

Is the above output possible?

Vinod P
  • 89
  • 6

2 Answers2

2

I would suggest you bind_rows() from dplyr:

library(dplyr)
#Data 1
asd1 <- data.frame(a = c("a","b"), b = c("fd", "fg"))
#Data 2
asd2 <- data.frame(a = c("a","b"), e = c("fd", "fg"), c = c("gfd","asd"))
#Bind
df <- bind_rows(asd1,asd2)

Output:

  a    b    e    c
1 a   fd <NA> <NA>
2 b   fg <NA> <NA>
3 a <NA>   fd  gfd
4 b <NA>   fg  asd
Duck
  • 39,058
  • 13
  • 42
  • 84
2
library(dplyr)

bind_rows(asd1, asd2, .id = "data")


#    data a    b    e    c
# 1     1 a   fd <NA> <NA>
# 2     1 b   fg <NA> <NA>
# 3     2 a <NA>   fd  gfd
# 4     2 b <NA>   fg  asd
Jingxin Zhang
  • 234
  • 2
  • 3