R - 将列表转换为数据帧

时间:2017-11-27 01:10:31

标签: r list dataframe

我有一个列表,其中包含所有包含四个元素的列表。它看起来像这样:

> summary(allMorans)
                      Length Class  Mode
trait1                 4      -none- list
trait2                 4      -none- list
trait3                 4      -none- list
traitB                 4      -none- list
traitX                 4      -none- list

这四个元素是某个统计测试的结果,包含“观察”,“预期”,“sd”,“pvalue”等元素。

如果我这样做:

MoransResults <- as.data.frame(allMorans)

我得到一个很长的行,看起来像这样:

 trait1.observed    trait1.expected    trait1.sd      trait1.pvalue       trait2.observed    trait2.expected   trait2.sd      trait2.pvalue    ...etc  
 0.1                0.2                0.01           0.09                0.3                0.2               0.01           0.07             ...etc

但是,我需要将此列表列表转换为如下所示的数据框:

TRAIT    observed   expected   sd     pvalue
trait1   0.1        0.2        0.01   0.09
trait2   0.3        0.2        0.01   0.07
trait3   0.1        0.1        0.01   0.55
traitB   0.2        0.2        0.01   0.49
traitX   0.3        0.2        0.01   0.07

我如何实现这一目标?

更新

根据评论中的要求,这里有一些示例数据:

> dput(allMorans)
structure(list(trait1 = structure(list(observed = -0.00820649454281412, 
expected = -0.0001000100010001, sd = 6.44860382275647e-05, 
p.value = 0), .Names = c("observed", "expected", "sd", "p.value"
)), trait2 = structure(list(observed = -0.16378930443073, expected = -0.0001000100010001, 
sd = 6.44860728086603e-05, p.value = 0), .Names = c("observed", 
"expected", "sd", "p.value")), trait3 = structure(list(observed = -0.348047732487769, 
expected = -0.0001000100010001, sd = 6.44872069930741e-05, 
p.value = 0), .Names = c("observed", "expected", "sd", "p.value"
))), .Names = c("trait1", "trait2", "trait3"))

1 个答案:

答案 0 :(得分:4)

另一种选择:

t(simplify2array(allMorans))

#           observed     expected             sd   p.value
#trait1 -0.008206495  -0.00010001   6.448604e-05      0      
#trait2 -0.1637893    -0.00010001   6.448607e-05      0      
#trait3 -0.3480477    -0.00010001   6.448721e-05      0