Hi: What about
colSums(mymat != 0) ? # Example: x <- matrix(sample(c(-1, 0, 1, 2), 100, replace = TRUE, prob = c(0.1, 0.8, 0.07, 0.03)), nrow = 25) which(x != 0) # 17 nonzero elements in this matrix [1] 9 17 27 32 36 41 44 45 49 50 62 67 68 72 76 78 82 colSums(x != 0) [1] 2 8 4 3 Dennis On Sun, Jun 26, 2011 at 3:15 AM, C6H5NO2 <c6h5...@gmail.com> wrote: > Hi R users, > > I want to know whether there is a fast method to compute the nonzeroes for > each column of dgCMatrix. > > For summation or average I can use colSums or colMeans. To count the > non-zeroes I write a function > > colCounts <- function(Mat) { > M1 <- apply(Mat, MARGIN=2, FUN=nnzero) > } > > But it seems this is quite slow because the apply function would transform a > dgCMatrix to a matrix. > > So I come here to ask if there is anybody know some fast method. > > -- > View this message in context: > http://r.789695.n4.nabble.com/columnwise-nnzero-for-dgCMatrix-tp3625726p3625726.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.