Reputation: 575
I have an column vector with following format in R: num [1:2464, 1].
I want to diagonal the vector, so each element is in the diagonal of the matrix. I have tried the following code:
diagvector <- diag(myvector)
But then it just show the first number. I think I only can use that code if my vector have the following form: num [1:2464].
So how do I a) change the format from num [1:2464, 1] to num [1:2464] for my vector, or b) take the diagonal to my vector with the format num [1:2464, 1]?
Upvotes: 2
Views: 1257
Reputation: 1414
Your "column vector" is actually a matrix as it has two dimensions, but it can be formed into a vector.
myvector <- matrix(1:2464, 1)
diagvector <- diag(c(myvector))
diagvector
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] ...
[1,] 1 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 2 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 3 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 4 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 5 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 6 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 7 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 8 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 9 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 10 0 0 0
[11,] 0 0 0 0 0 0 0 0 0 0 11 0 0
[12,] 0 0 0 0 0 0 0 0 0 0 0 12 0
[13,] 0 0 0 0 0 0 0 0 0 0 0 0 13
...
Or:
myvector <- matrix(1:2464, 1)
diagvector <- diag(length(myvector)) * c(myvector)
diagvector
Upvotes: 3