Count the number of non-zero elements of each column

后端 未结 3 1851
时光说笑
时光说笑 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)

    0 讨论(0)
  • 2020-12-05 07:28

    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
    
    0 讨论(0)
  • 2020-12-05 07:47

    with x being a column or vector;

    length(which(x != 0))

    0 讨论(0)
提交回复
热议问题