将矢量和数字列表(从复制)转换为数据帧

时间:2017-08-16 19:53:19

标签: r list dataframe lapply

在某些数据上运行replicate()函数[lapply()的近亲]后,我得到了一个看起来像这样的输出

myList <- structure(list(c(55L, 13L, 61L, 38L, 24L), 6.6435972422341,  c(37L,  1L, 57L, 8L, 40L), 5.68336098665417, c(19L, 10L, 23L, 52L, 60L ),
        5.80430476680636, c(39L, 47L, 60L, 14L, 3L), 6.67554407822367, 
        c(57L, 8L, 53L, 6L, 2L), 5.67149520387856, c(40L, 8L, 21L, 
        17L, 13L), 5.88446015238962, c(52L, 21L, 22L, 55L, 54L), 
        6.01685181395007, c(12L, 7L, 1L, 2L, 14L), 6.66299948053721, 
        c(41L, 46L, 21L, 30L, 6L), 6.67239635545512, c(46L, 31L, 
        11L, 44L, 32L), 6.44174324641076), .Dim = c(2L, 10L), .Dimnames = list(
        c("reps", "score"), NULL))

在这种情况下,整数向量是进入我不会进入的函数的索引,而标量浮点数是得分。

我喜欢看起来像

的数据框
Index 1 Index 2 Index 3 Index 4 Index 5 Score

55      13      61      38      24      6.64

37      1       57      8       40      5.68

19      10      23      52      60      5.80

等等。

或者,索引的矩阵和值的数组也可以。

对我来说没有用的东西。

 data.frame(t(random.out)) # just gives a data frame with a column of vectors and another of scalars

 cbind(t(random.out)) # same as above

 do.call(rbind, random.out) # intersperses vectors and scalars

我意识到其他人有类似的问题, 例如。 Convert list of vectors to data frame  但我无法找到这种特殊类型的矢量和标量的例子。

1 个答案:

答案 0 :(得分:3)

myList[1,]是一个向量列表,因此您可以将它们合并到一个包含do.callrbind的矩阵中。 myList[2,]是单个分数列表,因此您可以将它们合并到unlist的矢量中:

cbind(as.data.frame(do.call(rbind, myList[1,])), Score=unlist(myList[2,]))
#    V1 V2 V3 V4 V5    Score
# 1  55 13 61 38 24 6.643597
# 2  37  1 57  8 40 5.683361
# 3  19 10 23 52 60 5.804305
# 4  39 47 60 14  3 6.675544
# 5  57  8 53  6  2 5.671495
# 6  40  8 21 17 13 5.884460
# 7  52 21 22 55 54 6.016852
# 8  12  7  1  2 14 6.662999
# 9  41 46 21 30  6 6.672396
# 10 46 31 11 44 32 6.441743