Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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:

> df[,2]

[1] 2 5 8

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

1 Answer

0 votes
by

To get the index of a column you can use the  grep and colnames function as follows:

 

 m <- data.frame(A = c(1,4,7), B= c(2,5,8), C = c(3,6,9))

 m

  A B C

1 1 2 3

2 4 5 6

3 7 8 9

 

grep("B", colnames(df))

 [1] 2

or use

grep("^B$", colnames(df)) 

[1] 2

31k questions

32.4k answers

501 comments

693 users

Browse Categories

...