Gin_Salmon
Gin_Salmon

Reputation: 847

Convert multiple elements of a list into a matrix R

I've got a list, for example:

    [[1]]
              [,1]
[1,] -1.775291e-04
[2,] -1.267184e-04
[3,] -1.573868e-03
[4,]  4.157234e-02
[5,] -4.864003e-02
[6,]  2.316697e-05

[[2]]
              [,1]
[1,] -0.0010882973
[2,]  0.0009780598
[3,]  0.0003006506
[4,]  0.1579244926
[5,]  0.1655930418
[6,] -0.0006471336

[[3]]
              [,1]
[1,]  2.861335e-03
[2,] -3.259585e-05
[3,]  3.377353e-03
[4,]  1.224368e-02
[5,]  6.205352e-02
[6,] -3.028701e-04

[[4]]
              [,1]
[1,]  0.0023484525
[2,] -0.0007958971
[3,]  0.0038275408
[4,] -0.1705923272
[5,] -0.0706761005
[6,] -0.0004604092

I'd like to change this so that I have a matrix where each list becomes the first row of the data table, essentially I'd like to transpose each element of the list and then put them on top of one another so that I can handle them later.

Upvotes: 2

Views: 374

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269461

If L is the list then:

t(simplify2array(L))

No packages are used.

Upvotes: 2

CephBirk
CephBirk

Reputation: 6710

If d is your list:

d = list(matrix(rnorm(6), ncol = 1), matrix(rnorm(6), ncol = 1),matrix(rnorm(6), ncol = 1),matrix(rnorm(6), ncol = 1))

Then just use this:

t(sapply(d, c))

will result in a 4x6 matrix.

            [,1]       [,2]        [,3]       [,4]        [,5]       [,6]
[1,] -0.02910676 -0.8722619 -1.48340110 -1.9914850  0.80751174 -1.1062207
[2,] -0.38604263  0.6417695  0.02404823 -0.3484978 -1.03931644  1.0919702
[3,]  0.19229699  0.3389690  1.68451808  0.7688967  0.01010725 -0.3203104
[4,]  0.36910577 -0.4922259  0.81362335 -1.9770308  0.65197010  0.2063001

Upvotes: 2

Related Questions