【问题标题】:Unnest list and gather items with purrr使用 purrr 取消嵌套列表并收集项目
【发布时间】:2019-05-30 16:19:57
【问题描述】:

我有一个类似的列表:

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")))

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

goals player season 
42    a      88
52    b      88
.
.
41    a      89
53    b      89
.

我可以使用plyr 来实现这一点,例如: plyr::ldply(mylist, data.frame, .id="season"

我认为可能有一种更新的方法可以使用purrrdplyr

【问题讨论】:

  • 你能给我们你名单中的dput(listname)吗?不得不从头开始重新创建数据结构来回答问题并不好玩。

标签: r tidyverse purrr


【解决方案1】:

我们可以通过使用map循环通过listlist元素转换为tibble来做到这一点

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

base R 选项将转换为 listdata.frames 然后 rbind

do.call(rbind, lapply(lst1, as.data.frame))

数据

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))

【讨论】:

    【解决方案2】:

    使用 do.call、rbind 和来自 base R 的 Map 以及来自 dplyr 的 as_tibble 的另一种方法:

    do.call(rbind,Map(as_tibble,lst1))
    # A tibble: 7 x 3
      goals season player
      <int> <chr>  <chr> 
    1    42 88     a     
    2    52 88     b     
    3    55 88     c     
    4    41 89     a     
    5    53 89     b     
    6    37 89     c     
    7    40 89     d    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2021-02-27
      • 2021-12-13
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多