【问题标题】:Converting a list of vectors and numbers (from replicate) into a data frame将向量和数字列表(来自复制)转换为数据框
【发布时间】:2017-08-16 19:53:18
【问题描述】:

在一些数据上运行 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 但我找不到将这种特殊类型的向量和标量结合在一起的示例。

【问题讨论】:

  • 我会回到replicate 并使用simplify=FALSE。您可以更轻松地处理该结果。
  • 取消列出并填充矩阵...as.data.frame(matrix(unlist(myList), ncol = 6, byrow = T))

标签: r list dataframe lapply


【解决方案1】:

myList[1,] 是一个向量列表,因此您可以使用do.call 和rbind 将它们组合成一个矩阵。 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2015-04-01
    • 2022-08-03
    • 2021-06-25
    • 1970-01-01
    • 2020-11-02
    相关资源
    最近更新 更多