Identify Columns Index Matching Given Vector of String

10,163

Solution 1

try

 which(colnames(sample_matrix) %in% x)

Solution 2

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

which(colnames(sample_matrix) %in% x)

Or, alternatively, match

match(x, colnames(sample_matrix))

Solution 3

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".

Share:
10,163
user1234440
Author by

user1234440

asking the right questions while providing no help to others

Updated on June 16, 2022

Comments

  • user1234440
    user1234440 about 2 years

    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?