代码之家  ›  专栏  ›  技术社区  ›  ahmohamed

dplyr:包含rbind_all和bind_行的列表到数据帧的列表

  •  2
  • ahmohamed  · 技术社区  · 7 年前

    我想将一个命名列表列表转换为一个数据框,其中有些缺少列。我可以成功地做到这一点 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
    

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

    2 回复  |  直到 7 年前
        1
  •  3
  •   mt1022    7 年前

    请在中阅读此示例 ?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
    
        2
  •  0
  •   www    7 年前

    以下是一个使用 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
    
    推荐文章