Count the number of non-zero elements of each column

with x being a column or vector;

length(which(x != 0))


Another method using plyr's numcolwise:

library(plyr)

dat <- data.frame(a = sample(1:25, 25),
                  b = rep(0, 25),
                  c = sample(1:25, 25))
nonzero <- function(x) sum(x != 0)
numcolwise(nonzero)(dat)
   a b  c
1 25 0 25

What about:

apply(your.matrix, 2, function(c)sum(c!=0))

Does this help?

edit:

Even better:

colSums(your.matrix != 0)

edit 2:

Here we go, with an example for ya:

> example = matrix(sample(c(0,0,0,100),size=70,replace=T),ncol=7)
> example
      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0  100    0    0  100    0  100
 [2,]  100    0    0    0    0    0  100
 [3,]    0    0    0    0    0    0  100
 [4,]    0  100    0    0    0    0    0
 [5,]    0    0  100  100    0    0    0
 [6,]    0    0    0  100    0    0    0
 [7,]    0  100  100    0    0    0    0
 [8,]  100    0    0    0    0    0    0
 [9,]  100  100    0    0  100    0    0
[10,]    0    0    0    0    0  100    0
> colSums(example != 0)
[1] 3 4 2 2 2 1 3

(new example, the previous example with '1' values was not suited to show that we are summing the number of cells, not their contents)

Tags:

R