diag
Diagonal Matrices

Description

Creates a diagonal matrix or extracts the diagonal elements of a matrix.

Usage

diag(x = 1, nrow, ncol, names = TRUE)
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.
names a logical value used only when x is a matrix. If TRUE (the default) and the row and column names of input matrix are identical (as with the return value of the var function), then attach those names to the output vector. If FALSE never attach names to the output vector.
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
See Also
col, length, matrix, ncol.
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
Package base version 6.0.0-69
Package Index