1

After running the replicate() function [a close relative of lapply()] on some data I ended up with an output that looks like this

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))

In this case the vectors of integers are indexes that went into a function that I won't get into and the scalar-floats are scores.

I'd like a data frame that looks like

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

and so on.

Alternatively, a matrix of the indexes and an array of the values would be fine too.

Things that haven't worked for me.

 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

I realize other people have similar problems, eg. Convert list of vectors to data frame but I can't quite find an example with this particular kind of vectors and scalars together.

josliber
  • 43,891
  • 12
  • 98
  • 133
ohnoplus
  • 1,205
  • 1
  • 17
  • 29
  • I would go back to `replicate` and use `simplify=FALSE`. You'll have an easier time manipulating that result. – Rich Scriven Aug 16 '17 at 19:54
  • Unlist and fill a matrix... `as.data.frame(matrix(unlist(myList), ncol = 6, byrow = T))` –  Aug 16 '17 at 20:07

1 Answers1

3

myList[1,] is a list of vectors, so you can combine them into a matrix with do.call and rbind. myList[2,] is a list of single scores, so you can combine them into a vector with 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
josliber
  • 43,891
  • 12
  • 98
  • 133