Home > Enterprise >  How to extract column index of a dataframe with the variable name?
How to extract column index of a dataframe with the variable name?

Time:10-17

I would like to extract the column index of a variable of a dataframe using the variable name.

here is the df for exemple:

>df 

  Mean  Var  Max
a  1     0.5  3
b  1.5   0.4  4
c  0.7   0.3  2.5
d  0.3   0.1  0.5

I want to "reverse" this:

> variable.names(df[2])
[1] "Var"

with something like that:

> variable.names(df$Var)
NULL

But getting "2" instead of "NULL"

thanks for your help!!

CodePudding user response:

Use match:

match("Var", colnames(df))

CodePudding user response:

This should do it using which

df <- data.frame(Mean=c(1,1.5,0.7,0.3),Var=c(0.5,0.4,0.3,0.1),Max=c(3,4,2.5,0.5))
df

  Mean Var Max
1  1.0 0.5 3.0
2  1.5 0.4 4.0
3  0.7 0.3 2.5
4  0.3 0.1 0.5


which(colnames(df)=="Var")

Output:

[1] 2

CodePudding user response:

Similar to LMc( 1) solution -> We could use grep:

grep("Var", colnames(df))

output:

[1] 2
  • Related