nnzero The Number of Non-Zero Values of a Matrix
 Description
Returns the number of non-zero values of a numeric-like R object, and in particular an object x inheriting from class Matrix. 
Usage
nnzero(x, na.counted = NA)
Arguments
| x | an R object, typically inheriting from class  | 
| na.counted | a  
 For sparse matrices, you may often want to use  | 
Value
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). 
Methods
- signature(x = "ANY")
- 
the default method for non- Matrixclass objects, simply counts the number0s inx, countingNA's depending on thena.countedargument, see above.
- signature(x = "denseMatrix")
- 
conceptually the same as for traditional matrixobjects, care has to be taken for"symmetricMatrix"objects.
- 
signature(x = "diagonalMatrix"), andsignature(x = "indMatrix")
- 
fast simple methods for these special "sparseMatrix"classes.
- signature(x = "sparseMatrix")
- 
typically, the most interesting method, also carefully taking "symmetricMatrix"objects into account.
See Also
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. 
Examples
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)
    Copyright (©) 1999–2012 R Foundation for Statistical Computing.
Licensed under the GNU General Public License.