diag
Diagonal Matrices
Description
Creates a diagonal matrix or extracts the diagonal elements of a matrix.
Usage
diag(x = 1, nrow, ncol)
diag(x) <- value
Arguments
x |
a matrix, vector, or one-dimensional array. Missing values (NAs) are
allowed. If you do not provide a value for x, you must specify a
value for nrow.
|
nrow |
an integer that specifies the number of rows for the output matrix.
|
ncol |
an integer that specifies the number of columns for the output matrix.
if you do not specify a value for ncol, the value you specified
for nrow is used. In this case, 1s are placed on the
diagonal of the result.
|
value |
a vector or one-dimensional array whose length is the minimum of the
number of rows and the number of columns. Missing values (NAs) are
allowed.
|
Details
By default, the matrix is square with zeros off the diagonal, but it can
be made rectangular by specifying nrow and ncol.
The diag(x) <- value form allows replacement of the values on the
diagonal of a matrix.
Value
- If x is a matrix, returns the vector of diagonal elements of
x.
- If x is a vector or one-dimensional array of length greater
than one, returns a matrix with x on its diagonal and zeroes
elsewhere.
- If x is a vector or one-dimensional array of length one, and
you do not specify values for either nrow or ncol, returns
an x by x identity matrix.
See Also
Examples
amat <- matrix(c(12,15,6,10,2,9), nrow = 2)
diag(amat) # extract diagonal elements ((1,1),(2,2),etc.)
diag(diag(amat)) # create a square matrix with
# diagonal of amat
diag(5) # 5 by 5 identity matrix
diag(nrow = 5) # same thing
diag(as.matrix(5)) # 5
x <- 1:3
diag(x, nrow = 2*length(x)) # replicate x on the diagonal of a matrix
diag(x, nrow = length(x)) # put x on the diagonal of a matrix
bmat <- matrix(1:4,2)
diag(amat) <- diag(bmat) # put diagonal of bmat into diagonal of amat