histelheim
histelheim

Reputation: 5088

Best way of storing 100 matrices in R?

I'm writing a function that generates 100 matrices. Once I have this, I need to loop through the first superdiagonal on each matrix and extract the values. These values are supposed to go into a dataframe - 1 column for each superdiagonal. Let me illustrate:

First Matrix (The positions labeled as X should be extracted)

     [,1] [,2] [,3] [,4]
[1,]  1    X   .2   .1
[2,] .7   .8    X   .5
[3,] .6   .9   .4    X
[4,] .5   .1   .1   .2

So I need to loop through 100 of these matrices, get all the positions of each matrix labeled as X (first superdiagonal) and then I need to put each first superdiagonal in a data frame like this:

Output dataframe

         matrix1 matrix2 matrix3
[1,2]    .5      .2      .1
[2,3]    .5      .1      .2
[3,4]    .3      .7      .8

Given this scenario, what is the best way of storing the 100 matrices that I will later access to create the output dataframe? Objects? A dataframe consisting of matrices?

Additionally - are there other factors besides the one that I have posted that impacts my choice of data structure?

Upvotes: 1

Views: 308

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55350

Writing from my phone, but you can try this:

as.data.frame(lapply(matrixList, function(M) diag(M[, -1]) ))

Alternatively, if they are all exactly 10x10, you can substitute this as the 'function(M)` above

    M[(1:9)*11] 

Upvotes: 3

Related Questions