Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the column number in R given the column name [duplicate]

Tags:

r

Possible Duplicate:
Get column index from label in a data frame

I need to get the column number of a column given its name.

Supose we have the following dataframe:

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

I need a function that would work like the following:

getColumnNumber(df,"b") 

And it would return

[1] 2 

Is there a function like that?

Thanks!

like image 826
João Daniel Avatar asked Feb 14 '12 13:02

João Daniel


People also ask

How do I get column column numbers in R?

To get number of columns in R Data Frame, call ncol() function and pass the data frame as argument to this function. ncol() is a function in R base package.

How do I find duplicate columns in R?

The second method to find and remove duplicated columns in R is by using the duplicated() function and the t() function. This method is similar to the previous method. However, instead of creating a list, it transposes the data frame before applying the duplicated() function.

How do I extract columns by column names in R?

To select a column in R you can use brackets e.g., YourDataFrame['Column'] will take the column named “Column”. Furthermore, we can also use dplyr and the select() function to get columns by name or index. For instance, select(YourDataFrame, c('A', 'B') will take the columns named “A” and “B” from the dataframe.

How do I find the number of columns in a DataFrame in R?

The ncol() function in R programming That is, ncol() function returns the total number of columns present in the object.


2 Answers

which( colnames(df)=="b" ) 

Should do it.

like image 96
Ari B. Friedman Avatar answered Sep 21 '22 18:09

Ari B. Friedman


One fast and neat method is :

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

That avoids the vector scan that == and which do. If you have a lot of columns, and you do this a lot, then you might like the fastmatch package.

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

fmatch is faster than match, but on subsequent calls it's not just faster, it's instant.

like image 35
Matt Dowle Avatar answered Sep 21 '22 18:09

Matt Dowle