Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of non-zero elements of each column

Tags:

r

Very new to R and I have a .rda file that contains a matrix of gene IDs and counts for each ID in 96 columns. It looks like this:

enter image description here

I want to get separate counts for the number of non-zero items in each column. I've been trying the sum() function in a loop, but perhaps I don't understand loop syntax in R. Any help appreciated. Thanks!

Forest

like image 807
Forest Avatar asked Mar 09 '14 19:03

Forest


People also ask

How do you count non zero elements in Matlab?

N = nnz( X ) returns the number of nonzero elements in matrix X .

Which function will be used to count non zero values in a Dataframe?

Call sum() function on this bool Series object. It will give the count of total non-zero values in it, and that will be equal to the count of non-zero values in the selected column.

How do I count the number of zeros in a column in R?

Data Visualization using R Programming First of all, create a data frame. Then, use colSums function to find the number of zeros in each column.


2 Answers

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)

like image 152
Jealie Avatar answered Oct 25 '22 11:10

Jealie


with x being a column or vector;

length(which(x != 0))

like image 28
Ayse Ozhan Avatar answered Oct 25 '22 12:10

Ayse Ozhan