Suppose I have the following data frame:
df <- data.frame(A = c(1, 2, 3), B = c("a", "b", "c"), C = c(4, 5, 6))
A B C
1 1 a 4
2 2 b 5
3 3 c 6
If I wanted to know the position of a column e.g. column B, then I can use:
which(names(df)=="B")
Or
grep("B", names(df))
In both cases, I get 2
, but what if I wanted to know the positions of columns A and C at the same time? That is, I want to enter a vector of column names, and get a vector of their positions. So, if I entered "A", "C"
, the result should be 1 3
.
The two above examples I've used don't seem to work when entering a vector of column names instead of a single one.
I know I can do this with loops, but is there a method that achieves better performance?