Back
Say we have the following data frame:
> df A B C1 1 2 32 4 5 63 7 8 9
> 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
> df[,2]
[1] 2 5 8
Is there a way to get the index (2) from the column label ('B')?
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 C1 1 2 32 4 5 63 7 8 9 grep("B", colnames(df)) [1] 2or usegrep("^B$", colnames(df)) [1] 2
m <- data.frame(A = c(1,4,7), B= c(2,5,8), C = c(3,6,9))
m
grep("B", colnames(df))
[1] 2
or use
grep("^B$", colnames(df))
31k questions
32.8k answers
501 comments
693 users