【问题标题】:bind rows of tibbles present in nested list绑定嵌套列表中存在的小标题行
【发布时间】:2022-01-21 07:01:17
【问题描述】:

我生成了包含三个小标题的mylist

创建mylist后,如何通过分别绑定mylist的所有As、Bs、Cs行来创建三个小标题A_completeB_completeC_complete

mylist <- list()
for (iter in 1:10)
{
  mylist[[iter]] <- list(A = tibble(x = runif(5)),
                         B = tibble(x = rep("B", 2)),
                         C = tibble(x = 0:iter))
}

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    使用lapply

    A_complete = lapply(mylist, function(x) x[['A']]) %>% bind_rows()
    B_complete = lapply(mylist, function(x) x[['B']]) %>% bind_rows()
    C_complete = lapply(mylist, function(x) x[['C']]) %>% bind_rows()
    

    【讨论】:

      【解决方案2】:

      这对purrr::transpose() 很有用。这是一个简单的 tidyverse 解决方案。

      library(tidyverse)
      complete_data = mylist %>% 
        transpose() %>% 
        map(reduce, bind_rows)
      

      输出:

      > complete_data$A
      # A tibble: 50 x 1
              x
          <dbl>
       1 0.905 
       2 0.102 
       3 0.923 
       4 0.504 
       5 0.187 
       6 0.945 
       7 0.0668
       8 0.596 
       9 0.131 
      10 0.220 
      # ... with 40 more rows
      

      同样,complete_data$Bcomplete_data$C 也可用。

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-10
        • 2019-08-07
        • 2018-10-17
        相关资源
        最近更新 更多