Luther_Blissett
Luther_Blissett

Reputation: 327

How to pull the column indices when matching the rows of a dataframe and a vector

Say I have a dataframe of letters like so:

  X1 X2 X3
1  G  A  C
2  G  T  C
3  G  T  C
4  A  T  G
5  A  C  G

And a vector like so: ref <- c("A", "C", "C", "A", "G")

Going row-wise, how do I pull the column indices of the dataframe which match the vector?

So the answer should be a vector of numbers like so: 2, 3, 3, 1, 3

Upvotes: 1

Views: 28

Answers (1)

akrun
akrun

Reputation: 886938

We can use

max.col(df1 == ref)
#[1] 2 3 3 1 3

data

df1 <- structure(list(X1 = c("G", "G", "G", "A", "A"), X2 = c("A", "T", 
"T", "T", "C"), X3 = c("C", "C", "C", "G", "G")), class = "data.frame",
row.names = c("1", 
"2", "3", "4", "5"))

Upvotes: 1

Related Questions