Get column index from label in data frame

Say we have the following data frame:

> df ABC 1 1 2 3 2 4 5 6 3 7 8 9 

We can select column "B" from its index:

 > df[,2] [1] 2 5 8 

Is there a way to get index (2) from column label ('B')?

+69
r
Dec 13 '10 at 9:09
source share
4 answers

you can get the index via grep and colnames :

 grep("B", colnames(df)) [1] 2 

or use

 grep("^B$", colnames(df)) [1] 2 

to get columns called "B" without those containing B, for example. "ABC".

+100
Dec 13 '10 at 9:35
source share

This will do the following:

 which(colnames(df)=="B") 
+82
Dec 13 '10 at 9:40
source share

I wanted to see all the indexes for colnames because I needed to do a complex column permutation, so I printed the code names as a data frame. Growth names are indexes.

 as.data.frame(colnames(df)) 1 A 2 B 3 C 
+7
Aug 24 '17 at 19:51 on
source share

This seems to be an efficient way to list vars with column number:

 cbind(names(df)) 

Output:

  [,1] [1,] "A" [2,] "B" [3,] "C" 

Sometimes I like to copy position variables to my code, so I use this function:

 varnums<- function(x) {w=as.data.frame(c(1:length(colnames(x))), paste0('# ',colnames(x))) names(w)= c("# Var/Pos") w} varnums(df) 

Output:

 # Var/Pos # A 1 # B 2 # C 3 
+2
Jun 01 '18 at 20:53
source share



All Articles