简体   繁体   English

将列表列表转换为 data.frame 或 tibble (R) 的单个嵌套行

[英]Convert list of lists into single nested row of a data.frame or tibble (R)

I have a nested list of lists:我有一个嵌套的列表列表:

data = list(a = list(1, 2, 3), b = list("foo"), c = list("toast", "onions"))

How can I convert this into a single row of a data.frame or tibble?如何将其转换为 data.frame 或 tibble 的单行? I would like the lists with more than one element ( a and c here) to be kept as lists, and the single-element ( b ) to be a regular value.我希望将具有多个元素(此处为ac )的列表保留为列表,并将单个元素 ( b ) 保留为常规值。

Expected output is:预期输出为:

# A tibble: 1 x 3
  a          b     c         
  <list>     <chr> <list>    
1 <list [3]> foo   <list [2]>

What about this?那这个呢?

> as_tibble_row(Map(function(x) ifelse(length(x)==1,unlist(x),list(x)),data))
# A tibble: 1 x 3
  a          b     c
  <list>     <chr> <list>
1 <list [3]> foo   <list [2]>
data[] <- lapply(data, function(x) if (length(x) == 1) x[[1]] else list(x))
data.table::setDF(data)

# > str(data)
# 'data.frame': 1 obs. of  3 variables:
#  $ a:List of 1
#   ..$ :List of 3
#   .. ..$ : num 1
#   .. ..$ : num 2
#   .. ..$ : num 3
#  $ b: chr "foo"
#  $ c:List of 1
#   ..$ :List of 2
#   .. ..$ : chr "toast"
#   .. ..$ : chr "onions"

You can use enframe + pivot_wider您可以使用enframe + pivot_wider

tibble::enframe(data) %>% tidyr::pivot_wider() 
#      a          b          c         
#  <list>     <list>     <list>    
#1 <list [3]> <list [1]> <list [2]>

To get length one column as vector we can add :要获得一列作为向量的长度,我们可以添加:

library(dplyr)

tibble::enframe(data) %>% 
  tidyr::pivot_wider() %>%
  summarise(across(.fns = ~if(length(unlist(.)) == 1) unlist(.) else .))

#      a          b     c         
#  <list>     <chr> <list>    
#1 <list [3]> foo   <list [2]>

一个选项是创建一个两列数据集,从base R aggregate

aggregate(values ~ ind, stack(data), list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM