1

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!

1
  • This also might work: colnames(df)[grep(df$favourite, df[1:3])] The output: [1] "flavour2" Commented Oct 12, 2020 at 8:33

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.