Get column index from label in a data frame
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".
The following will do it:
which(colnames(df)=="B")