Extract or replace the diagonal of a matrix, or construct a diagonal matrix.
diag(x = 1, nrow, ncol) diag(x) <- value
- a matrix, vector or 1D array, or missing.
- nrow, ncol
- Optional dimensions for the result when
xis not a matrix.
- either a single value or a vector of length equal to that of the current diagonal. Should be of a mode which can be coerced to that of
diag has four distinct usages:
xis a matrix, when it extracts the diagonal.
xis missing and
nrowis specified, it returns an identity matrix.
xis a scalar (length-one vector) and the only argument, it returns a square identity matrix of size given by the scalar.
xis a numeric vector, either of length at least 2 or there were further arguments. This returns a matrix with the given diagonal and zero off-diagonal entries.
The replacement form sets the diagonal of the matrix
x to the given value(s).
In all other cases the value is a diagonal matrix with
nrow rows and
ncol columns (if
ncol is not given the matrix is square). Here
nrow is taken from the argument if specified, otherwise inferred from
x: if that is a vector (or 1D array) of length two or more, then its length is the number of rows, but if it is of length one and neither
ncol is specified,
nrow = as.integer(x).
When a diagonal matrix is returned, the diagonal elements are one except in the fourth case, when
x gives the diagonal elements: it will be recycled or truncated as needed, but fractional recycling and truncation will give a warning.
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
Documentation reproduced from R 3.0.2. License: GPL-2.