dplyr:带有rbind_all和bind_rows的数据帧矢量列表

时间:2019-03-07 01:58:59

标签: r dplyr

我想将命名列表的列表转换为数据框,其中某些列表缺少列。我可以使用已弃用的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行为?

2 个答案:

答案 0 :(得分:4)

请在?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

答案 1 :(得分:0)

这是使用map_dfr软件包中的purrr的一种解决方法。

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