我有一个尺寸为4000x1的列向量,我需要用该向量制作一个矩阵,但矩阵需要将列向量作为对角线,其他数字作为零。像这样:
列矢量
> vector <- matrix(c(1:5), ncol=1, nrow=5)
> vector
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
矩阵
[,1] [,2] [,3] [,4]
a 1 0 0 0
b 0 2 0 0
c 0 0 3 0
如何生成此输出?
答案 0 :(得分:3)
这听起来像diag()
函数,例如,
> my_vect <- 1:5
> diag(my_vect)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 2 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 4 0
[5,] 0 0 0 0 5
顺便说一句,正如你所写的那样vector
实际上是一个5x1矩阵,所以你需要把它转换成一个矢量:
> diag(as.vector(vector))
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 2 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 4 0
[5,] 0 0 0 0 5