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!
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.
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.
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.
The ncol() function in R programming That is, ncol() function returns the total number of columns present in the object.
which( colnames(df)=="b" )
Should do it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With