How to create a list of matrix in R

52,504

Try

x <- matrix(1:10, ncol=2)
y <- x+300

MATS <- list(x, y) # use 'list' instead of 'c' to create a list of matrices
MATS
[[1]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

[[2]]
     [,1] [,2]
[1,]  301  306
[2,]  302  307
[3,]  303  308
[4,]  304  309
[5,]  305  310

Here you have to refer to MATS[[1]] as if it were x

If you want to append a new matrix to the exiting list try

z <- x+500
MATS[[3]] <- z  # appeding a new matrix to the existing list
MATS

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

[[2]]
     [,1] [,2]
[1,]  301  306
[2,]  302  307
[3,]  303  308
[4,]  304  309
[5,]  305  310

[[3]]
     [,1] [,2]
[1,]  501  506
[2,]  502  507
[3,]  503  508
[4,]  504  509
[5,]  505  510

One drawback of this approach is that you have to know the position in the list where you have to append the new matrix, if you don't know it or simply if you dont want this approach, then here's a trick:

unlist(list(MATS, list(z)), recursive=FALSE) # will give u the same list :D
Share:
52,504
ManInMoon
Author by

ManInMoon

Updated on July 19, 2022

Comments

  • ManInMoon
    ManInMoon almost 2 years

    I want to create a list of 2D matrices

    > x
         [,1] [,2]
    [1,]    1    6
    [2,]    2    7
    [3,]    3    8
    [4,]    4    9
    [5,]    5   10
    
    > y
         [,1] [,2]
    [1,]  301  306
    [2,]  302  307
    [3,]  303  308
    [4,]  304  309
    [5,]  305  310
    
    > MATS<-c(x,y)
    
    > MATS[1]
    [1] 1
    

    I would like to be able to refer to MATS[1] as if it where x...

  • ManInMoon
    ManInMoon over 11 years
    @jiber Thank you. And if I want to append another matrix to list? What would be the syntax please? I do this in a loop.
  • metaforge
    metaforge over 9 years
    @Jilber thanks. How about reading in such a thing from a text or csv file?
  • vk087
    vk087 almost 8 years
    Is there any way to read second column of all matrices at once ?
  • Jilber Urbina
    Jilber Urbina almost 8 years
    @vk087 Looking for something like this... lapply(MATS, function(x) x[,2,drop=FALSE])?