Search code examples
rmatrixblocknames

Build block matrix from existing matrixes and retain dimnames in r


I'm building a block matrix with several smaller matrices that I past along the diagonal with the package Matrix

Let's say I have two matrices

m1=matrix(runif(10*10),nrow=10,ncol=10)
m2=matrix(runif(5*5),nrow=5,ncol=5)

I create a block matrix with

M<-bdiag(m1,m2)

How do I retain the names of columns and rows from the smaller m1 and m2 to the block matrix M?

note that I need M in a dataframe and therefore I also need at the end to run

M<-as.data.frame(as.matrix(M))

Thanks!


Solution

  • Add the dimnames back in after running bdiag (assuming you mean Matrix::bdiag):

    m1 <- matrix(1:9,nrow=3,dimnames=list(LETTERS[1:3],LETTERS[1:3]))
    m2 <- matrix(1:4,nrow=2,dimnames=list(LETTERS[4:5],LETTERS[4:5]))
    m1
    
    #  A B C
    #A 1 4 7
    #B 2 5 8
    #C 3 6 9
    
    m2
    #  D E
    #D 1 3
    #E 2 4
    
    out <- bdiag(m1,m2)
    dimnames(out) <- Map(c, dimnames(m1), dimnames(m2))
    out
    
    #5 x 5 sparse Matrix of class "dgCMatrix"
    #  A B C D E
    #A 1 4 7 . .
    #B 2 5 8 . .
    #C 3 6 9 . .
    #D . . . 1 3
    #E . . . 2 4