I have a nx1 matrix I want to convert this to a nxn diagonal matrix in R
In your case, where the original vector contains identical elements, it suffices to multiply the n x n Identity matrix by 0.25 as the comments suggested.
But the general case of a vector with non-identical elements is more interesting:
Denote your n x 1 column vector by v = (v_1,...,v_n)'. Then, define the n x n matrix E_i as a matrix having 1 in its [i,i] element and zeros everywhere else. Also define the n x 1 column vector e_i as a vector having 1 in the [i] position (row) and zeros everywhere else.
Then the n x n matrix V = diag(v_1,...,v_n) can be obtained as
where the sum is over i=1,...n
As @Ben Bolker has suggested, you can simply define your identity matrix using diag
:
my.matrix <- diag(0.25, 4)
my.matrix
## [,1] [,2] [,3] [,4]
## [1,] 0.25 0.00 0.00 0.00
## [2,] 0.00 0.25 0.00 0.00
## [3,] 0.00 0.00 0.25 0.00
## [4,] 0.00 0.00 0.00 0.25
If you just want to know how to do this in R
, it's:
my.matrix <- matrix(0, nrow=4, ncol=4)
diag(my.matrix) <- rep(0.25, 4)