【问题标题】:Convert list of list object to dataframe in R将列表对象列表转换为R中的数据框
【发布时间】:2018-06-09 19:08:14
【问题描述】:

我有一个列表,如下所示。我想将它转换成所需格式的数据框。

我的列表:

[[1]]
NULL

[[2]]
[[2]]$`file`
[1] "ABC"

[[2]]$New
[1] 21

[[2]]$Old
[1] 42


[[3]]
[[3]]$`file`
[1] "CDF"

[[3]]$NEW
[1] 206

[[3]]$Old
[1] 84

我想将此列表对象列表转换为所需格式的数据框:

file   New   Old
ABC    21     42
CDF    206    84

提前致谢!

【问题讨论】:

  • @RichScriven,谢谢它的工作,从下一次我会放可重现的例子。
  • R - list to data frame的可能重复
  • 不完全。这是一个嵌套列表。
  • @RichScriven 检查 Ian Sudbery 答案
  • 当然。如果你喜欢长而复杂的代码。

标签: r list dataframe


【解决方案1】:

我们可以在转换成tibble后使用map_df

library(tidyverse)
myList %>% 
   map_df(as_tibble)
# A tibble: 2 x 3
#  file    New   Old
#  <chr> <dbl> <dbl>
#1 ABC      21    42
#2 CDF     206    84

或者bind_rows

bind_rows(myList)
# A tibble: 2 x 3
#  file    New   Old
#  <chr> <dbl> <dbl>
#1 ABC      21    42
#2 CDF     206    84

数据

myList <- list(NULL, list(file = 'ABC', New = 21, Old = 42), 
                      list(file = 'CDF', New = 206, Old = 84))

【讨论】:

    【解决方案2】:

    类似(ls 是您的列表):

    df <- data.frame(matrix(unlist(ls), ncol = max(lengths(ls)), byrow = TRUE))
    

    如果列名很重要,那么

    names(df) <- names(ls[[which(lengths(ls)>0)[1]]])
    

    【讨论】:

    • Warning message: In matrix(unlist(myLIST), ncol = max(lengths(myLIST)), byrow = TRUE) : data length [20000] is not a sub-multiple or multiple of the number of rows [1000]
    【解决方案3】:

    看起来下面的方法可行。

    do.call(rbind, lapply(list, as.data.frame))
    

    list 是您的列表。

    【讨论】:

    • Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 1, 0
    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2018-12-19
    相关资源
    最近更新 更多