I have an n x p
matrix that looks like this:
n = 100
p = 10
x <- matrix(sample(c(0,1), size = p*n, replace = TRUE), n, p)
I want to create an n x p x p
array A
whose k
th item along the 1st dimension is a p x p
diagonal matrix containing the elements of x[k,]
. What is the most efficient way to do this in R? I'm looking for a way that uses outer
(or some other vectorized approach) rather than one of the apply
functions.
Solution using lapply
:
A <- aperm(simplify2array(lapply(1:nrow(x), function(i) diag(x[i,]))), c(3,2,1))
I'm looking for something more efficient than this.
Thanks.