Determine whether columns match a specified row vector

I have a row vector

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

and I have a matrix with several columns l; which contains the names in this string vector. I would like to get the column numbers / index that match their names.

which(colnames(sample_matrix) == x)

This is higher if x is not a vector, but a single element. Any solutions?

+5
source share
3 answers

try

 which(colnames(sample_matrix) %in% x)
+7
source

also:

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

Using grep is often more general to test for the presence of values ​​in a string. You can get all the elements matching the pattern and all the names starting with the character “a”.

+2
source

, , %in% :

which(colnames(sample_matrix) %in% x)

, , match

match(x, colnames(sample_matrix))
+1

All Articles