nnzero                package:Matrix                R Documentation

_T_h_e _N_u_m_b_e_r _o_f _N_o_n-_Z_e_r_o _V_a_l_u_e_s _o_f _a _M_a_t_r_i_x

_D_e_s_c_r_i_p_t_i_o_n:

     Returns the number of non-zero values of a numeric-like R object,
     and in particular an object 'x' inheriting from class 'Matrix'.

_U_s_a_g_e:

     nnzero(x, na.counted = NA)

_A_r_g_u_m_e_n_t_s:

       x: an R object, typically inheriting from class 'Matrix' or
          'numeric'.

na.counted: a 'logical' describing how 'NA's should be counted.  There
          are three possible settings for 'na.counted':

          _T_R_U_E 'NA's _are_ counted as non-zero (since "they are not
               zero").

          _N_A (default)the result will be 'NA' if there are 'NA''s in
               'x' (since "NA's are not known, i.e., _may be_ zero").

          _F_A_L_S_E 'NA's are _omitted_ from 'x' before the non-zero
               entries are counted.

          For sparse matrices, you may often want to use 'na.counted =
          TRUE'. 

_V_a_l_u_e:

     the number of non zero entries in 'x' (typically 'integer').

     Note that for a _symmetric_ sparse matrix 'S' (i.e., inheriting
     from class 'symmetricMatrix'), 'nnzero(S)' is typically _twice_
     the 'length(S@x)'.

_S_e_e _A_l_s_o:

     The 'Matrix' class also has a 'length' method; typically,
     'length(M)' is much larger than 'nnzero(M)' for a sparse matrix M,
     and the latter is a better indication of the _size_ of 'M'.

_E_x_a_m_p_l_e_s:

     m <- Matrix(0+1:28, nrow = 4)
     m[-3,c(2,4:5,7)] <- m[ 3, 1:4] <- m[1:3, 6] <- 0
     (mT <- as(m, "dgTMatrix"))
     nnzero(mT)
     (S <- crossprod(mT))
     nnzero(S)
     str(S) # slots are smaller than nnzero()
     stopifnot(nnzero(S) == sum(as.matrix(S) != 0))# failed earlier

     data(KNex)
     M <- KNex$mm
     class(M)
     dim(M)
     length(M); stopifnot(length(M) == prod(dim(M)))
     nnzero(M) # more relevant than length
     ## the above are also visible from
     str(M)

