6

I've got a vector of string

x<-c('a','b')

and I have an matrix with multiple columnsl; which contains names in that vector of string. I would like to get the column numbers/index which matches their names.

which(colnames(sample_matrix) == x)

This above works when x is not a vector but a single element. Any solutions?

smci
  • 32,567
  • 20
  • 113
  • 146
user1234440
  • 22,521
  • 18
  • 61
  • 103

3 Answers3

8

try

 which(colnames(sample_matrix) %in% x)
Aditya Sihag
  • 5,057
  • 4
  • 32
  • 43
3

What you are looking for is %in% as in:

which(colnames(sample_matrix) %in% x)

Or, alternatively, match

match(x, colnames(sample_matrix))
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
2

Also:

grep("^a$|^b$", colnames(sample_matrix) )

Using grep is often more general that testing for presence in a string of values. You can get all the items that match a pattern, say all names that begin with "a".

IRTFM
  • 258,963
  • 21
  • 364
  • 487