Well, you can either store arrays in a list or an array.
With the array the idea would be to use a three-dimensional array. The third dimension would be an indexer of the matrices. However, for this solution, all matrices have to be equal in size.
For example, the command below generates an array that can be interpreted as follows: it stores 10 matrices 2 x 2.
matrizes <- array(dim= c(2,2,10))
Then you can popular this array by indexing in the third dimension:
set.seed(1)
for (i in 1:10){
matrizes[,,i] <- matrix(rnorm(4), ncol=2)
}
Thus, to access the first matrix:
matrizes[,,1]
[,1] [,2]
[1,] -0.6264538 -0.8356286
[2,] 0.1836433 1.5952808
or the tenth matrix
matrizes[,,10]
[,1] [,2]
[1,] -0.3942900 1.1000254
[2,] -0.0593134 0.7631757
The other option is as you said yourself, to store in a list. Lists are very flexible in R, so if you want to store other objects together with the matrices, or if the matrices are of different sizes, the list is more suitable.
matrizes <- list()
set.seed(1)
for (i in 1:10){
matrizes[[i]] <- matrix(rnorm(4), ncol=2)
}
Accessing the matrix 1:
matrizes[[1]]
[,1] [,2]
[1,] -0.6264538 -0.8356286
[2,] 0.1836433 1.5952808
And the matrix 10:
matrizes[[10]]
[,1] [,2]
[1,] -0.3942900 1.1000254
[2,] -0.0593134 0.7631757
In this case, as you can see in my code, I have no way to determine the dimensions of the matrices... they will be generated within the for() command.. The idea is that I reserve a list with 10 generic matrices and then replace each one with a matrix of a random dimension... I could even create a list with the 10 matrices of 4x2 and then try to replace, but gives 10 errors: In ucs_educ_niveis[i] <- subset(inf_ucs_com_criancas_em_escola_2, : number of items to replace is not a Multiple of Replacement length
– orrillo
@Vasco if the matrices are of different sizes then it has to be by list even, just run the loop as I put in the example, replacing the
matrix(rnorm(4), ncol=2)
at your command.– Carlos Cinelli
I get it... thank you
– orrillo