11
$\begingroup$

In a data frame, I would like to get the column's index by name. For example:

x <- data.frame(foo=c('a','b','c'),bar=c(4,5,6),quux=c(4,5,6))

I want to know the column index for "bar".

I came up with the following but it seems inelegant. Is there a more straightforward builtin that I am missing?

seq(1,length(names(x)))[names(x) == "bar"]
[1] 2
$\endgroup$
4
  • 3
    $\begingroup$ match("bar",names(x)) also works, though match is much more useful when the first argument is also a vector. $\endgroup$
    – cardinal
    Commented Apr 25, 2011 at 1:35
  • $\begingroup$ Do you actually need the column's index? You can also use x[,"bar"] to get the entire column, similar to the usual x\$bar. And in both cases, subscript the rows: x[2:3, "bar"] or x\$bar[2:3]. If you need to feed the index to a routine that requires an index, that's not helpful, of course. $\endgroup$
    – Wayne
    Commented Apr 25, 2011 at 14:57
  • $\begingroup$ Bah, it keeps messing up my dollar signs. The bottom line is that there are two ways to use a column's name the dollar sign method and including it as a subscript. $\endgroup$
    – Wayne
    Commented Apr 26, 2011 at 16:53
  • 3
    $\begingroup$ This question appears to be off-topic because it is about how to do something in R, & not about any related statistical issues. $\endgroup$ Commented Oct 2, 2013 at 13:43

2 Answers 2

22
$\begingroup$

probably this is the simplest way:

which(names(x)=="bar")
$\endgroup$
12
$\begingroup$

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.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.