gpt4 book ai didi

r - 使用 purrr 取消嵌套列表并收集项目

转载 作者:行者123 更新时间:2023-12-04 18:00:52 24 4
gpt4 key购买 nike

我有一个列表,如:

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 ?

最佳答案

我们可以通过转换 list 来做到这一点。元素到 tibble通过循环遍历 list使用 map

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.frame s 然后 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))

关于r - 使用 purrr 取消嵌套列表并收集项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54033096/

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