如何取消嵌套列列表? [英] How to unnest column-list?

查看:49
本文介绍了如何取消嵌套列列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像:

tibble(a = c('first', 'second'), 
       b = list(c('colA' = 1, 'colC' = 2), c('colA'= 3, 'colB'=2))) 

# A tibble: 2 x 2
  a      b        
  <chr>  <list>   
1 first  <dbl [2]>
2 second <dbl [2]>

哪一个想变成这种形式:

Which a would like to turn into this form:

# A tibble: 2 x 4
  a       colA  colB  colC
  <chr>  <dbl> <dbl> <dbl>
1 first     1.   NA     2.
2 second    3.    2.   NA 

我尝试使用 unnest(),但是我遇到了从嵌套值中保留元素名称的问题.

I tried to use unnest(), but I am having issues preserving the elements' names from the nested values.

推荐答案

您可以通过将列表列中的元素强制为按您喜欢的方式排列的数据框来实现这一点,这将很好地取消嵌套:

You can do this by coercing the elements in the list column to data frames arranged as you like, which will unnest nicely:

library(tidyverse)

tibble(a = c('first', 'second'), 
       b = list(c('colA' = 1, 'colC' = 2), c('colA'= 3, 'colB'=2))) %>% 
    mutate(b = invoke_map(tibble, b)) %>% 
    unnest()
#> # A tibble: 2 x 4
#>   a       colA  colC  colB
#>   <chr>  <dbl> <dbl> <dbl>
#> 1 first     1.    2.   NA 
#> 2 second    3.   NA     2.

执行强制转换有点棘手,因为您不想以 2x1 数据帧结束.有多种方法可以解决这个问题,但直接的路由是 purrr::invoke_map,它调用带有 purrr::invoke 的函数(如 do.callcode>) 在列表中的每个元素上.

Doing the coercion is a little tricky, though, as you don't want to end up with a 2x1 data frame. There are various ways around this, but a direct route is purrr::invoke_map, which calls a function with purrr::invoke (like do.call) on each element in a list.

这篇关于如何取消嵌套列列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆