Count the number of non-zero elements of each column

后端 未结 3 1855
时光说笑
时光说笑 2020-12-05 06:42

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:

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 07:21

    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)

提交回复
热议问题