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 = n)
     diag(x) <- value

_A_r_g_u_m_e_n_t_s:

       x: a matrix, vector or 1D array.

nrow, ncol: Optional dimensions for the result.

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

_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 row names.

     If 'x' is a vector (or 1D array) of length two or more, then
     'diag(x)' returns a diagonal matrix whose diagonal is 'x'.

     If 'x' is a vector of length one then 'diag(x)' returns an
     identity matrix of order the nearest integer to 'x'.  The
     dimension of the returned matrix can be specified by 'nrow' and
     'ncol' (the default is square).

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

_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=rnorm(5))))#-> vector with names "X" and "Y"
     rownames(M) <- c(colnames(M),rep("",3));
     M; diag(M) #  named as well

