Unnest列表并使用purrr收集项目

Dom*_*o55 5 r purrr tidyverse

我有一个列表,如:

list(list(goals = c(42L, 52L, 55L), 
          season = "88", 
          player = c("a", "b","c")), 
     list(goals = c(41L,53L, 37L, 40L), 
          season = "89", 
          player = c("a","b", "c", "d")))
Run Code Online (Sandbox Code Playgroud)

我想将其转换为长格式的数据帧,如:

goals player season 
42    a      88
52    b      88
.
.
41    a      89
53    b      89
.
Run Code Online (Sandbox Code Playgroud)

我可以用以下方式实现这一点plyr: plyr::ldply(mylist, data.frame, .id="season"

我想可能有更新的方式使用purrrdplyr

akr*_*run 6

我们可以通过循环使用来转换list元素tibblelistmap

library(tidyverse)
lst1 %>%
    map_df(as_tibble)
# A tibble: 7 x 3
#  goals player season
#  <dbl> <chr>   <dbl>
#1    42 a          88
#2    52 b          88
#3    55 c          88
#4    41 a          89
#5    53 b          89
#6    37 c          89
#7    48 d          89
Run Code Online (Sandbox Code Playgroud)

一个base R选择是转换成listdata.frame秒,然后rbind

do.call(rbind, lapply(lst1, as.data.frame))
Run Code Online (Sandbox Code Playgroud)

数据

lst1 <- list(list(goals = c(42, 52, 55), player = c("a", "b", "c"), season = 88), 
     list(goals = c(41, 53, 37, 48), player = c("a", "b", "c", 
     "d"), season = 89))
Run Code Online (Sandbox Code Playgroud)