just to add another possibility:
You can usually use grep
and it's decedents (i.e., grepl, to do these kind of jobs in a more sophisiticated way using regular expressions.
On your example your could get the column index with:
grep("^bar$", colnames(x))
or grep("^bar$", names(x))
The ^
and $
are meta characters for the beginning and end of a string, respectively.
Check ?grep and especially ?regex for more infos (i.e., you can grab only partial names/matches, or the return value is the string itself or a logical vector,...)
For me, grep
is more R-ish.
Strongly related is the recent package by Hadley Wickhem: stringr, A package for "modern, consistent string processing" including grep like functions. He recently published a paper on it in the R Journal.
See also my answer on stackoverflow on an identical issue.
match("bar",names(x))
also works, thoughmatch
is much more useful when the first argument is also a vector. $\endgroup$