Home > database >  How to find the number of columns of an R matrix that contains values greater than or equal to a giv
How to find the number of columns of an R matrix that contains values greater than or equal to a giv

Time:06-30

I have a matrix with 52 columns, and 5,000 rows. I want to find the number of columns that contain a value less than or equal to a value (for example, how many columns out of 52 contain a number less than or equal to 10)

I was trying rowSum but I cannot remember / find a way to make this work.

Thanks!

CodePudding user response:

A possible solution:

m <- matrix(1:9, 3, 3)

sum(colSums(m <= 5) != 0)

#> [1] 2

CodePudding user response:

How about writing your own function?

Here's the code.

count_rows = function(df, val)
{
    checks = 0
    for (i in 1:ncol(df))
    {
       if(any(df[,i] > 0))
          checks = checks   1
    }
    return (checks)
}

A = matrix(runif(100), 10, 10)

count_rows(A, 0.5)

CodePudding user response:

Say the matrix mat of dimensions 5000x52

set.seed(1234)
mat <- matrix(trunc(runif(5000*52)*1e5) , 5000 , 52)

dim(mat)

#> [1] 5000   52

then we can find how many columns out of 52 contains a number less than or equal to 10 using

sum(apply(mat , 2 , \(x) any(x <= 10)))

#> 24
  • Related