如何将列表列表转换为数据框 - 不相同列表

2024-03-14

我有一个列表,其中每个元素都是命名列表,但元素在各处并不相同。我已阅读有关如何将列表列表转换为数据帧的解决方案here https://stackoverflow.com/questions/4512465/what-is-the-most-efficient-way-to-cast-a-list-as-a-data-frame?rq=1 and here https://stackoverflow.com/questions/4227223/r-list-to-data-frame,但是当列表不相同时,这些都不起作用。

示例 - 请注意,我也有混合类型,如果解决方案将所有内容强制为字符,那就没问题了。

lisnotOK <- list(list(a=1, b=2, c="hi"), list(b=2, c="hello", d="nope"))

结果应该简单地具有 NA,其中列不能由列表填充,就像rbind.fill来自 plyr,或rbind_all来自 dplyr。

Example

lisOK <- list(list(a=1, b=2, c="hi"), list(a=3, b=5, c="bye"))

# One of many solutions
do.call(rbind.data.frame, lisOK)

# gives
   a b   c
2  1 2  hi
21 3 5 bye

任何使用的解决方案rbind,或试图使lisnotOK进入矩阵将会失败,而上面链接的帖子中的任何示例都不起作用,即使我尝试使用rbind_all or rbind.fill.

一种解决方案是一个丑陋的 for 循环,其中每个连续列表都更改为数据帧,并使用rbind_all绑定到数据框。

有谁知道有效的解决方案?


任何函数使用data.frame(.)在绑定之前对列表的每个元素进行处理将是非常低效的(更不用说不必要的了)。这是另一种使用方法data.table's rbindlist(从 v1.9.3 开始)您可以获得here https://github.com/Rdatatable/data.table.

require(data.table) ## 1.9.3
rbindlist(lisnotOK, fill=TRUE)
#     a b     c    d
# 1:  1 2    hi   NA
# 2: NA 2 hello nope

它适用于列表列表(如本问题)、data.frames 和 data.tables。

如果不是这个,那么我会选择阿南达的list2mat函数(如果您的类型全部相同)。


阿南达的基准L2 data:

fun1 <- function(inList) ldply(inList, as.data.frame)
fun2 <- function(inList) list2mat(inList)
fun3 <- function(inList) rbindlist(inList, fill=TRUE)
fun4 <- function(inList) rbind_all(lapply(inList, as.data.frame))

microbenchmark(fun1(L2), fun2(L2), fun3(L2), fun4(L2), times = 10)
# Unit: milliseconds
#      expr         min          lq      median          uq         max neval
#  fun1(L2) 1927.857847 2161.432665 2221.999940 2276.241366 2366.649614    10
#  fun2(L2)   12.039652   12.167613   12.361629   12.483751   16.040885    10
#  fun3(L2)    1.225929    1.374395    1.473621    1.510876    1.858597    10
#  fun4(L2) 1435.153576 1457.053482 1492.334965 1548.547706 1630.443430    10

注:我用过as.data.frame(.)代替data.frame(.)(前者稍快一些)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将列表列表转换为数据框 - 不相同列表 的相关文章

随机推荐