diag
is generic.
diag(x, ...) diag.default(x = <<see below>>, nrow = <<see below>>, ncol=<<see below>>) diag(x) <- value
NA
s) are allowed.
NA
s) are allowed.
x
is a matrix,
the vector of diagonal elements of
x
;
if
x
is a vector of length greater than one,
a matrix with
x
on its diagonal and zeroes
elsewhere.
if
x
is a vector of length 1
and both
nrow
and
ncol
are missing,
the value is an
x
by
x
identity matrix.
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.
If
x
is missing,
then
nrow
must be given
and
ncol
equals
nrow
if it is also missing;
in this case
1
s are placed on the diagonal
of the result.
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 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 # works even if length(x) is 1 or x is a matrix diag(x) <- diag(y) # put diagonal of y into diagonal of x