将命名列表嵌套到数据框 [英] Nested named list to data frame

查看:24
本文介绍了将命名列表嵌套到数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下来自分析的命名列表输出.可复现的代码如下:

I have the following named list output from a analysis. The reproducible code is as follows:

list(structure(c(-213.555409754509, -212.033637890131, -212.029474755074, 
-211.320398316741, -211.158815833294, -210.470525157849), .Names = c("wasn", 
"chappal", "mummyji", "kmph", "flung", "movie")), structure(c(-220.119433774144, 
-219.186901747536, -218.743319709963, -218.088361753899, -217.338920075687, 
-217.186050877079), .Names = c("crazy", "wired", "skanndtyagi", 
"andr", "unveiled", "contraption")))

我想将其转换为数据框.我曾尝试使用 reshape2、dplyr 和其他用于将列表转换为数据框的解决方案取消列出数据框选项,但没有取得太大成功.我正在寻找的输出是这样的:

I want to convert this to a data frame. I have tried unlist to data frame options using reshape2, dplyr and other solutions given for converting a list to a data frame but without much success. The output that I am looking for is something like this:

  Col1        Val1      Col2          Val2
1 wasn      -213.55     crazy         -220.11
2 chappal   -212.03     wired         -219.18
3 mummyji   -212.02     skanndtyagi   -218.74

等等等等.实际输出有多个带有成对值的列,并运行到许多行中.我已经尝试过以下代码:

so on and so forth. The actual out put has multiple columns with paired values and runs into many rows. I have tried the following codes already:

do.call(rbind, lapply(df, data.frame, stringsAsFactors = TRUE)) 

works 部分提供列中的所有字符值和第二个中的数值.

works partially provides all the character values in a column and numeric values in the second.

data.frame(Reduce(rbind, df))

不起作用 - 提供第一个列表中的名称和两个列表中的数字作为两个不同的行

didn't work - provides the names in the first list and numbers from both the lists as tow different rows

colNames <- unique(unlist(lapply(df, names)))
M <- matrix(0, nrow = length(df), ncol = length(colNames), 
        dimnames = list(names(df), colNames))
matches <- lapply(df, function(x) match(names(x), colNames))
M[cbind(rep(sequence(nrow(M)), sapply(matches, length)),
    unlist(matches))] <- unlist(df)
M

没有正常工作.

有人可以帮忙吗?

推荐答案

由于列表元素的长度都相同,您应该能够将它们stack,然后按列组合.

Since the list elements are all of the same length, you should be able to stack them and then combine them by columns.

试试:

do.call(cbind, lapply(myList, stack))

这篇关于将命名列表嵌套到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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