2

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!

3 Answers3

2

A possible solution:

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

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

#> [1] 2
PaulS
  • 21,159
  • 2
  • 9
  • 26
  • colSums would give sum of the column. OP's question is about _any_ value in the column exceeding a value. – Harshvardhan Jun 29 '22 at 21:56
  • `colSums` will count how many values in each column are less or equal to 5. If these counts are not zero, then the column is counted as having at least one value less or equal to 5. Therefore, I think my code does what the OP asked for. – PaulS Jun 29 '22 at 22:02
0

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)
Harshvardhan
  • 479
  • 1
  • 3
  • 12
0

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
Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19