diag                  package:base                  R Documentation

_M_a_t_r_i_x _D_i_a_g_o_n_a_l_s

_D_e_s_c_r_i_p_t_i_o_n:

     Extract or replace the diagonal of a matrix, or construct a
     diagonal matrix.

_U_s_a_g_e:

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

_A_r_g_u_m_e_n_t_s:

       x: a matrix, vector or 1D array, or missing.

nrow, ncol: Optional dimensions for the result when 'x' is not a
          matrix.

   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'.

_D_e_t_a_i_l_s:

     'diag' has four distinct usages:

        1.  'x' is a matrix, when it extracts the diagonal.

        2.  'x' is missing and 'nrow' is specified, it returns an
           identity matrix.

        3.  'x' is a scalar (length-one vector) and the only argument
           it a square identity matrix of size given by the scalar.

        4.  'x' is a 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.

     It is an error to specify 'nrow' or 'ncol' in the first case.

_V_a_l_u_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 rownames.

     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 'nrow' nor '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.

_N_o_t_e:

     Using 'diag(x)' can have unexpected effects if 'x' is a vector
     that could be of length one. Use 'diag(x, nrow = length(x))' for
     consistent behaviour.

_R_e_f_e_r_e_n_c_e_s:

     Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) _The New S
     Language_. Wadsworth & Brooks/Cole.

_S_e_e _A_l_s_o:

     'upper.tri', 'lower.tri', 'matrix'.

_E_x_a_m_p_l_e_s:

     require(stats)
     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 = stats::rnorm(5))))
     #-> vector with names "X" and "Y"

     rownames(M) <- c(colnames(M),rep("",3));
     M; diag(M) #  named as well

