

   diag {base}                                  R Documentation

   MMaattrriixx DDiiaaggoonnaallss

   DDeessccrriippttiioonn::

        Extract or replace the diagonal of a matrix, or con-
        struct a diagonal matrix.

   UUssaaggee::

        diag(x, nrow, ncol)
        diag(x) <- value

   VVaalluuee::

        If `x' is a matrix then `diag(x)' returns the diagonal
        of `x'.  The resulting vector will have `names' if the
        matrix `x' has matching column and row names.

        If `x' is a vector (or a 1-d array) then `diag(x)'
        returns a diagonal matrix whose diagonal is `x'.  If
        `x' is an integer then `diag(x)' returns an identity
        matrix of order `x'.  The dimension of the returned
        matrix can be specified by `nrow' and `ncol' (the
        default is square).

        The assignment form sets the diagonal of the matrix `x'
        to the given value(s).

   SSeeee AAllssoo::

        `matrix'.

   EExxaammpplleess::

        dim(diag(3))
        diag(10,3,4) # guess what?
        all(diag(1:3) == {m <- matrix(0,3,3); diag(m) <- 1:3; m})

        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

