list - Diag function om multiple dimensions in R -


i use diag() function on list of vectors, list of matrices diagonals vectors of list.

to more specific, suppose have list called list of 100 vectors 14 values each.

>dim(list) 100 14 

i create array array of 100 matrices of size 14x14, diagonal of matrix diag2vec(array[i,,]) vector list[i,] (all other values in matrix 0).

so end with:

>dim(array) 100 14 14 

i tried using diag() function, cannot work row-wise.

(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 m matrix, not list, , dim applied last object returns 3 3 2, want think, instead of 2 3 3 in example.


Comments