合并不同列的多个数据框

时间:2020-09-05 12:36:30

标签: r

我们可以将多个数据框的行与不同的列组合吗?下面的例子

> 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

由于存在不同的列,现在出现错误。

预期产量

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

以上输出可能吗?

2 个答案:

答案 0 :(得分:2)

我建议您bind_rows()中的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)

输出:

  a    b    e    c
1 a   fd <NA> <NA>
2 b   fg <NA> <NA>
3 a <NA>   fd  gfd
4 b <NA>   fg  asd

答案 1 :(得分: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