jo_
jo_

Reputation: 731

How can I find which column contains the same value as another specified column in R?

I have a dataframe with only one row. How can I find which column contains the same value as another specified column in the same dataframe?

For example, I want to find which flavour is the favorite flavor in this df. The answer should be the column name flavour2 since it coincides with 'Apple':

df <- data.frame(flavour1 = c("Grape"),
                 flavour2 = c("Apple"),
                 flavour3 = c("Strawberry"),
                 favourite = c("Apple"))

Thank you!

Upvotes: 1

Views: 62

Answers (3)

akrun
akrun

Reputation: 886938

We can also use

names(df)[df$favourite == df[-length(df)]]
#[1] "flavour2"

Or using match

names(df)[match(df$favourite, unlist(df[-length(df)]))]
#[1] "flavour2"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

You can compare all the values in df with favourite column and return the corresponding column name.

names(which(df$favourite == unlist(df[-ncol(df)])))
#[1] "flavour2"

Upvotes: 1

Paul
Paul

Reputation: 2977

If you want to check which column has the same value as favourite, this might do the trick:

colnames(df)[grep(df$favourite, df[1:3])]

Output:

> colnames(df)[grep(df$favourite, df[1:3])]
[1] "flavour2"

grep(df$favourite, df[1:3]) returns the column index of df[1:3] that matches the value of df$favourite. Then, using this index, colnames(df)[] select the right column name.

Upvotes: 1

Related Questions