Get column index from label in a data frame

前端 未结 7 969
忘掉有多难
忘掉有多难 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: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".

提交回复
热议问题