简体   繁体   中英

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!

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.

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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM