R:将嵌套列表转换为数据框,并获取列表级别名称als因子 [英] R: Converting nested list to dataframe and get names of list levels als factors

查看:167
本文介绍了R:将嵌套列表转换为数据框,并获取列表级别名称als因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套列表:

list1 <- list("A"=c(1,1,1), "B"=c(2,2,2), "C"=c(3,3,3))
list2 <- list("F1" = list1, "F2" = list1)

我想将列表的最后一个级别(包含向量)作为数据框,我想获得列表的级别作为因素:

and I would like to get the last level of the list (containing the vector) as a dataframe and I would like to get the levels of the list as factors:

  Level1 Level2 V1 V2 V3
1     F1      A  1  1  1
2     F1      B  2  2  2
3     F1      C  3  3  3
4     F2      A  1  1  1
5     F2      B  2  2  2
6     F2      C  3  3  3

第一部分很好地给出了:

The first part is nicely given by:

data.frame(matrix(unlist(list2), ncol=3, byrow=T))

但是,我没有找到一个很好的方法,也可以将list-name-name作为同一数据帧中的因素。有任何想法吗? :

However, I did not find a nice way to also get the list-level-names as factors in the same dataframe. Any ideas? :)

编辑

推荐答案

融化从reshape2中有一个列表的方法。也许在这种情况下可以使用它。这样的东西:

melt from "reshape2" has a method for lists. Perhaps it can be used in this case. Something like this:

library(reshape2)
dcast(cbind(
  coln = sequence(rapply(list2, length)), 
  melt(list2)), L1 + L2 ~ coln, 
  value.var = "value")
#   L1 L2 1 2 3
# 1 F1  A 1 1 1
# 2 F1  B 2 2 2
# 3 F1  C 3 3 3
# 4 F2  A 1 1 1
# 5 F2  B 2 2 2
# 6 F2  C 3 3 3

这篇关于R:将嵌套列表转换为数据框,并获取列表级别名称als因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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