John legend2
John legend2

Reputation: 920

find columns meeting a condition in r

I am trying to get unique column names meeting a certain condition. For example, with this matrix M, I am trying to get the unique column having smaller than 5. From the matrix, my desiring outcome is a vector (a,b,c) - a from the first row, b from the second row, b from the thrid row c from the fifth row.

set.seed(1234)
M = matrix(sample(20,20), ncol=4)

   M
     [,1] [,2] [,3] [,4]
[1,]    3   10    7    9
[2,]   12    1    5   17
[3,]   11    4   20   16
[4,]   18    8   15   19
[5,]   14    6    2   13

colnames(M) = letters[1:4]

Upvotes: 1

Views: 579

Answers (1)

MKR
MKR

Reputation: 20095

One possibility using base-R can be as

M[,colSums(M<5)>0]

#       a  b  c
# [1,]  3 10  7
# [2,] 12  1  5
# [3,] 11  4 20
# [4,] 18  8 15
# [5,] 14  6  2

If OP wants to know just the names of columns meeting criteria then solution can be as:

colnames(M[,colSums(M<5)>0])
#[1] "a" "b" "c"

Upvotes: 2

Related Questions