-8

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.

Community
  • 1
  • 1
halo09876
  • 2,725
  • 12
  • 51
  • 71

5 Answers5

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
0

I found it.

which(names(train)%in% name of the variables in vector)
bbiasi
  • 1,549
  • 2
  • 15
  • 31
halo09876
  • 2,725
  • 12
  • 51
  • 71
0

Try this:

(1:length(all.names))[all.names %in% select.names]
bbiasi
  • 1,549
  • 2
  • 15
  • 31
gparker
  • 11
  • 2
-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)
bbiasi
  • 1,549
  • 2
  • 15
  • 31
sidquanto
  • 315
  • 3
  • 6