-1

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.

Chris
  • 13
  • 2

3 Answers3

0
(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.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
0

Too quick with first attempt.

Using library(abind)

library(abind)
abind(lapply(x, diag), along = 0)

where x is assumed to be your list of vectors

Neal Fultz
  • 9,282
  • 1
  • 39
  • 60
Nick F
  • 311
  • 2
  • 8
0

Assumming your data looks like this:

z <- replicate(100, runif(14), simplify=FALSE)

try:

z2 <- aperm(vapply(z, diag, diag(14)), 3:1) 

which has:

> dim(z2)
[1] 100  14  14
Neal Fultz
  • 9,282
  • 1
  • 39
  • 60