Get column index from label in a data frame

前端 未结 7 946
忘掉有多难
忘掉有多难 2020-12-04 05:49

Say we have the following data frame:

> df
  A B C
1 1 2 3
2 4 5 6
3 7 8 9

We can select column \'B\' from its index:

&g         


        
相关标签:
7条回答
  • 2020-12-04 06:26
    match("B", names(df))
    

    Can work also if you have a vector of names.

    0 讨论(0)
  • 2020-12-04 06:29

    Following on from chimeric's answer above:

    To get ALL the column indices in the df, so i used:

    which(!names(df)%in%c()) 
    

    or store in a list:

    indexLst<-which(!names(df)%in%c())
    
    0 讨论(0)
  • 2020-12-04 06:38

    you can get the index via grep and colnames:

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

    or use

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

    to only get the columns called "B" without those who contain a B e.g. "ABC".

    0 讨论(0)
  • 2020-12-04 06:44

    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 variables with position into 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
    
    0 讨论(0)
  • 2020-12-04 06:48

    Use t function:

    t(colnames(df))
    
         [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
    [1,] "var1" "var2" "var3" "var4" "var5" "var6"
    
    0 讨论(0)
  • 2020-12-04 06:50

    I wanted to see all the indices for the colnames because I needed to do a complicated column rearrangement, so I printed the colnames as a dataframe. The rownames are the indices.

    as.data.frame(colnames(df))
    
    1 A
    2 B
    3 C
    
    0 讨论(0)
提交回复
热议问题