简体   繁体   中英

How to find the number of columns of an R matrix that contains values greater than or equal to a given number?

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!

A possible solution:

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

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

#> [1] 2

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM