【问题标题】:Unnesting/rectangling/flattening a nested list using `tidyr::unnest_longer()`使用 `tidyr::unnest_longer()` 取消嵌套/矩形化/展平嵌套列表
【发布时间】:2023-02-06 13:17:01
【问题描述】:

我一直在努力了解tidyrtibblify 中的取消嵌套函数。我相信您应该能够使用 unnest_longer() 来复制下面将这种嵌套列表变成 tibble 的更多手动方法,但我一直在努力研究文档。如何执行此操作的正确示例将极大地帮助我:

# Example nested list
nl <- list(time = list("2023-02-06", "2023-02-07", "2023-02-08",
                       "2023-02-09", "2023-02-10", "2023-02-11",
                       "2023-02-12"), 
           precipitation_sum = list(0.9, 0, 0, 0.3, 0, 0, 0))

# one way to do it (extract colnames and construct)
tibble(!!! setNames(map(nl, unlist),names(nl)))

# another way (collect & reduce each sublist)
as_tibble(lapply(nl, function(x) Reduce(c, x)))

# how to use tidyr and unnest_longer? (below is incorrect)
unnest_longer(tibble(nl), col = everything())

【问题讨论】:

    标签: r tidyr nested-lists


    【解决方案1】:

    我们可以使用

    library(tibble)
    library(tidyr)
    as_tibble(nl) %>% 
        unnest(cols = where(is.list))
    

    -输出

    # A tibble: 7 × 2
      time       precipitation_sum
      <chr>                  <dbl>
    1 2023-02-06               0.9
    2 2023-02-07               0  
    3 2023-02-08               0  
    4 2023-02-09               0.3
    5 2023-02-10               0  
    6 2023-02-11               0  
    7 2023-02-12               0  
    

    或者更紧凑

    library(purrr)
    map_dfc(nl, unlist)
    # A tibble: 7 × 2
      time       precipitation_sum
      <chr>                  <dbl>
    1 2023-02-06               0.9
    2 2023-02-07               0  
    3 2023-02-08               0  
    4 2023-02-09               0.3
    5 2023-02-10               0  
    6 2023-02-11               0  
    7 2023-02-12               0  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 2020-09-06
      相关资源
      最近更新 更多