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:
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
N = nnz( X ) returns the number of nonzero elements in matrix X .
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.
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.
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)
with x
being a column or vector;
length(which(x != 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With