Get column number in R if column name

Possible duplicate:
Get column index from label in data frame

I need to get the column number with his name.

Suppose we have the following data file:

df <- data.frame(a=rnorm(100),b=rnorm(100),c=rnorm(100)) 

I need a function that will work as follows:

 getColumnNumber(df,"b") 

And he will return

 [1] 2 

Is there such a function?

Thank!

+38
r
Feb 14 '12 at 13:05
source share
4 answers
 which( colnames(df)=="b" ) 

Must do it.

+65
Feb 14 2018-12-12T00:
source share

One quick and neat method:

 > match("b",names(df)) [1] 2 

This avoids vector scanning by == and which . If you have many columns and you do this a lot, you might like the fastmatch package .

 > require(fastmatch) > fmatch("b",names(df)) [1] 2 

fmatch faster than match , but on subsequent calls it is not only faster, but also instant.

+50
Feb 14 2018-12-14T00:
source share

Another method that better generalizes inaccurate matching tasks is to use grep :

 grep("^b$", colnames(df) ) 

If you want the number of all column names starting with "b" to be deleted, you write:

 df[ , - grep("^b", colnames(df) )] 

This neatly fixes an issue where you cannot use negative indexing with character vectors.

+9
Feb 42-14 2018-12-14T00:
source share

.. especially if you need to get multiple column indices, the approach below applies:

 > df <- data.frame(a=rnorm(100),b=rnorm(100),c=rnorm(100)) > which(names(df)%in%c("b", "c")) [1] 2 3 

if you use this for a subset of df you don't need to ()

 > df_sub <- df[, names(df)%in%c("b", "c")] > head(df_sub) bc 1 0.1712754 0.3119079 2 -1.3656995 0.7111664 3 -0.2176488 0.7714348 4 -0.6599826 -0.3528118 5 0.4510227 -1.6438053 6 0.2451216 2.5305453 
+6
Feb 14 2018-12-12T00:
source share



All Articles