gpt4 book ai didi

r - 使用 `tidyr::unnest_longer()` 取消嵌套/矩形化/展平嵌套列表

转载 作者:行者123 更新时间:2023-12-02 01:24:04 25 4
gpt4 key购买 nike

我一直在尝试了解 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())

最佳答案

我们可以使用

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

关于r - 使用 `tidyr::unnest_longer()` 取消嵌套/矩形化/展平嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75357416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com