Search code examples
rlistwrite.table

How do I tell write.table to save the data of each list item in a separate row?


Let's say I have this array:

 my.array <- array(1:48, dim=c(3,4,4))

And after doing some awkward transformations I end up with the following data:

tarray <- apply(my.array, c(1,3), t)
listarray <-apply(tarray, 3, as.list)
ulist <- lapply(listarray, unlist)
trlist <- lapply(ulist, t)

[[1]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    4    7   10    2    5    8   11    3     6
     [,11] [,12]
[1,]     9    12

[[2]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]   13   16   19   22   14   17   20   23   15    18
     [,11] [,12]
[1,]    21    24

[[3]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]   25   28   31   34   26   29   32   35   27    30
     [,11] [,12]
[1,]    33    36

[[4]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]   37   40   43   46   38   41   44   47   39    42
     [,11] [,12]
[1,]    45    48

I want to save it so each list item gets its own row, i.e.

1 4 7 10 2 5 8 11 3 6 9 12 
13 16 19 22 14 17 20 23 15 18 21 24 
25 28 31 34 26 29 32 35 27 30 33 36
37 40 43 46 38 41 44 47 39 42 45 48

But when I use write.table(trlist, file="test", sep="/t", row.names=FALSE,col.names = FALSE, quote = FALSE) it just saves everything in a single row


Solution

  • We can do this by looping through the third dimension, extract the 'my.array' along that dimension, transpose, concatenate to vector and convert it to a single matrix by rbinding the list elements

    do.call(rbind, lapply(seq(dim(my.array)[3]), function(i) c(t(my.array[,,i]))))
    #      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
    #[1,]    1    4    7   10    2    5    8   11    3     6     9    12
    #[2,]   13   16   19   22   14   17   20   23   15    18    21    24
    #[3,]   25   28   31   34   26   29   32   35   27    30    33    36
    #[4,]   37   40   43   46   38   41   44   47   39    42    45    48
    

    Or another approach would be to use aperm and then convert it to matrix

    matrix(c(aperm(my.array, c(2, 1, 3))), nrow = 4, byrow = TRUE)