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
  • 29,564
  • 18
  • 109
  • 144
user1234440
  • 20,681
  • 18
  • 57
  • 98

3 Answers3

8

try

 which(colnames(sample_matrix) %in% x)
Aditya Sihag
  • 4,959
  • 4
  • 30
  • 41
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
  • 184,536
  • 28
  • 389
  • 466
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
  • 251,731
  • 20
  • 347
  • 472