0 votes
1 view
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 (25.3k points)

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...