Search code examples
rlistmatrixdiagonal

Diag function om multiple dimensions in R


I would like to use the diag() function on a list of vectors, so as to get a list of matrices where the diagonals are the vectors of my list.

To be more specific, suppose I have a list called list of 100 vectors with 14 values each.

>dim(list)
100 14

I would like to create an array array of 100 matrices of size 14x14, where the diagonal of the matrix diag2vec(array[i,,]) is my vector list[i,] (all other values in the matrix to be 0).

So I would end up with:

>dim(array)
100 14 14

I tried using the diag() function, but I cannot get it to work row-wise.


Solution

  • (M <- matrix(1:6, nrow = 2))
    #      [,1] [,2] [,3]
    # [1,]    1    3    5
    # [2,]    2    4    6
    sapply(1:nrow(M), function(i) diag(M[i, ]), simplify = "array")
    # , , 1
    # 
    #      [,1] [,2] [,3]
    # [1,]    1    0    0
    # [2,]    0    3    0
    # [3,]    0    0    5
    # 
    # , , 2
    # 
    #      [,1] [,2] [,3]
    # [1,]    2    0    0
    # [2,]    0    4    0
    # [3,]    0    0    6
    

    Also, note that M is a matrix, not a list, and that dim applied to the last object returns 3 3 2, which is what you really want I think, instead of 2 3 3 as in your example.