问题描述
限时送ChatGPT账号..要取消嵌套我可以使用的数据框:
To unnest a data frame I can use:
df <- data_frame(
x = 1,
y = list(a = 1, b = 2)
)
tidyr::unnest(df)
但是如何在数据框列内的列表中取消嵌套列表?
But how can I unnest a list inside of a list inside of a data frame column?
df <- data_frame(
x = 1,
y = list(list(a = 1, b = 2))
)
tidyr::unnest(df)
错误:
每列必须是向量列表或数据框列表 [y]
Each column must either be a list of vectors or a list of data frames [y]
推荐答案
使用 purrr
,这对列表来说很好,
With purrr
, which is nice for lists,
library(purrr)
df %>% dmap(unlist)
## # A tibble: 2 x 2
## x y
## <dbl> <dbl>
## 1 1 1
## 2 1 2
这或多或少相当于
as.data.frame(lapply(df, unlist))
## x y
## a 1 1
## b 1 2
<小时>
更新:
dmap
已被弃用并移至 purrrlyr,它是有趣但命运多舛的函数现在会向您发出大量弃用警告.您可以将基本的 R 习语翻译成 tidyverse:
dmap
has been deprecated and moved to purrrlyr, the home of interesting but ill-fated functions that will now shout lots of deprecation warnings at you. You could translate the base R idiom to tidyverse:
df %>% map(unlist) %>% as_data_frame()
在这种情况下可以正常工作,但不能超过一行(所有这些方法都面临一个问题).一个更强大的解决方案可能是
which will work fine for this case, but not for more than one row (a problem all these approaches face). A more robust solution might be
library(tidyverse)
df %>% bind_rows(df) %>% # make larger sample data
mutate_if(is.list, simplify_all) %>% # flatten each list element internally
unnest() # expand
#> # A tibble: 4 × 2
#> x y
#> <dbl> <dbl>
#> 1 1 1
#> 2 1 2
#> 3 1 1
#> 4 1 2
这篇关于在数据框列中取消嵌套列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论