dplyr: 使用rbind_all和bind_rows将向量列表转换为数据框

4

我想将一个具有缺失列的命名列表转换为数据框。我可以使用已弃用的rbind_all成功完成,但不能使用替代方法bind_rows

例子 缺少列的列表(el3缺少b

ex = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, c=5))

rbind_all(ex)
# A tibble: 3 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     2     3
2     2     3     4
3     3    NA     5


> bind_rows(ex)
Error in bind_rows_(x, .id) : Argument 3 must be length 3, not 2

没有丢失的列
ex2 = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, b=4, c=5))

rbind_all(ex2)
# A tibble: 3 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     2     3
2     2     3     4
3     3     4     5

bind_rows(ex2) # Output is transposed for some reason
# A tibble: 3 x 3
    el1   el2   el3
  <dbl> <dbl> <dbl>
1     1     2     3
2     2     3     4
3     3     4     5

如何使用非弃用的函数复制 rbind_all 的行为?

do.call(bind_rows, ex)? - Dan
2
问题在于你没有转换成“命名列表的列表”(这样可以工作),而是一个命名向量的列表。根据文档,你需要传递给 bind_rows “数据框、可能是数据框的列表或数据框的列表”。 - Ritchie Sacramento
@H1 感谢您发现了这个问题。我会编辑标题以反映这一点。 - ahmohamed
2个回答

8

请阅读关于?bind_rows的示例:

# Note that for historical reasons, lists containg vectors are
# always treated as data frames. Thus their vectors are treated as
# columns rather than rows, and their inner names are ignored:
ll <- list(
  a = c(A = 1, B = 2),
  b = c(A = 3, B = 4)
)
bind_rows(ll)

# You can circumvent that behaviour with explicit splicing:
bind_rows(!!!ll)

因此,在您的情况下,您可以尝试以下方法:
ex = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, c=5))
bind_rows(!!!ex)

# # A tibble: 3 x 3
#       a     b     c
#   <dbl> <dbl> <dbl>
# 1     1     2     3
# 2     2     3     4
# 3     3    NA     5

ex2 = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, b=4, c=5))
bind_rows(!!!ex2)

# # A tibble: 3 x 3
#       a     b     c
#   <dbl> <dbl> <dbl>
# 1     1     2     3
# 2     2     3     4
# 3     3     4     5

0
这里有一个解决方法,可以使用purrr包中的map_dfr。
library(dplyr)
library(purrr)

map_dfr(ex, ~as_tibble(t(.)))
# # A tibble: 3 x 3
#       a     b     c
#   <dbl> <dbl> <dbl>
# 1     1     2     3
# 2     2     3     4
# 3     3    NA     5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接