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')?
you can get the index via grep and colnames:
grep
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".
2.1m questions
2.1m answers
60 comments
57.0k users