如何在 R 中按行绑定具有不同列数的 tibbles

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

我想按行绑定 df1df2,保持相同的列名,以获得 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))

由 reprex 包 (v0.3.0) 创建于 2020-10-30

尝试使用 dplyr 中的 bind_rows()。更新了致谢 @AbdessabourMtk:

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

输出:

# 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

我们可以使用 data.table

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

-输出

#   a b  c
#1: 1 4  1
#2: 2 5  5
#3: 3 6  7
#4: 8 5 NA
#5: 9 6 NA

基本 R 选项

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

给予

> 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