I found partial answers in Get the column number in R given the column name and Get column index from label in a data frame but I couldn't find out how to do this for multiple variables. I tried putting all column names into a vector but that did not work.
Asked
Active
Viewed 1.1k times
-8
-
3Can you give a small example of what you're trying to do. What did you try? Where did you get stuck? – A5C1D2H2I1M1N2O1R2T1 Dec 04 '13 at 13:21
-
Please give examples ideally in code – chengcj Nov 20 '15 at 11:04
5 Answers
3
You should really use match()
.
match
returns a vector of the positions of (first) matches of its first argument in its second.
Syntax: match( your_names_of_interest, names(your_df) )
The other solution does not preserve order. To illustrate why this is bad
df <- data.frame(foo=1:3, bar=4:6, qux=7:9)
multiple_names <- c('qux','bar','foo')
match(multiple_names,names(df)) # returns 3 2 1 (correct)
which(names(df) %in% multiple_names) # returns 1 2 3 (INCORRECT)

C8H10N4O2
- 18,312
- 8
- 98
- 134
2
Try
View(colnames(dataframe))
This will output a table of the column numbers and column names

Peter
- 51
- 2
-
Can you add some context, perhaps showing how the output of this can be used? – mwotton Dec 10 '14 at 01:04
0
-2
let x be the data frame and column.names be the set of names whose number you want to find. the following does the job.
which(names(x) == column.names)