Stat Tistician
Stat Tistician

Reputation: 883

How to save different matrices in a variable using R?

I want to save different matrices into one variable, like an array, for example: I have matrix 1:

ma1<-matrix(c(1:8),4)

and matrix 2:

ma2<-matrix(c(2,1,3,4,5,6,4,5),4)

Now, I want to save these matrices into one more dimensional variable, so like this:

multiarray<-0
multiarray[1]<-ma1
multiarray[2]<-ma2

(I want to do this later on with a loop.)

It would be important, that the single output, e.g. multiarray[1] is again a matrix. How can I do this?

Upvotes: 1

Views: 3319

Answers (1)

Ogglord
Ogglord

Reputation: 66

A simple list would suffice

ma1<-matrix(c(1:8),4)
ma2<-matrix(c(2,1,3,4,5,6,4,5),4)
ma3<-matrix(runif(8),4)

either assign like this:

multiarray = list(ma1,ma2);

or in a loop

multiarray = list();
for(...){
   multiarray[[i]] = maX;
}

or by name

multiarray = list();     
multiarray$something = ma3; # ma3 will implicitly have first index 1

the output is a matrix

multiarray[[1]]

Upvotes: 4

Related Questions