Extract or replace the diagonal of a matrix, or construct a diagonal matrix.
diag(x = 1, nrow, ncol, names = TRUE)
diag(x) <- value
| Parameter | Description |
|---|---|
x |
a matrix, vector or 1D array, or missing. |
nrow, ncol |
optional dimensions for the result when x is not a matrix. |
names |
(when x is a matrix) logical indicating if the resulting vector, the diagonal of x, should inherit names from dimnames(x) if available. |
value |
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 x. |
# NOT RUN {
dim(diag(3))
diag(10, 3, 4) # guess what?
all(diag(1:3) == {m <- matrix(0,3,3); diag(m) <- 1:3; m})
## other "numeric"-like diagonal matrices :
diag(c(1i,2i)) # complex
diag(TRUE, 3) # logical
diag(as.raw(1:3)) # raw
(D2 <- diag(2:1, 4)); typeof(D2) # "integer"
require(stats)
## diag(<var-cov-matrix>) = variances
diag(var(M <- cbind(X = 1:5, Y = rnorm(5))))
#-> vector with names "X" and "Y"
rownames(M) <- c(colnames(M), rep("", 3))
M; diag(M) # named as well
diag(M, names = FALSE) # w/o names
# }