Search for a value in the same row of a dataframe and return the name of the column that matches

GOALS: I have a dataframe where I added an extra column (minIget) with the minimum value between 3 selected columns (T1, T2, T3). Now, I want to know how to add another column where it compares the minimum value obtained with the values of the 3 columns T1, T2 and T3, and returns me the name of the column with which the minimum value of the minIget column matches.

CONTEXT:

> data <- read.csv("JSSP-Entrenamiento(2021).csv", stringsAsFactors = TRUE)
> head(data)
T1                    T2                  T3
30691236    158195       35967032
6092311      984994       68731713
33770        11222493     1562254
80158         15396912     870488
3550276    409118        22433488
11869532   1184782    117060533
> data <- data %>% mutate(minIget = pmin(T1, T2,T3))
> head(data)
 T1                            T2                        T3                       minIget
30691236          158195            35967032                158195
6092311              984994            68731713               984994
33770                11222493              1562254               33770
80158               15396912               870488                80158
3550276              409118              22433488            409118
11869532           1184782            117060533          1184782

This is where I get stuck, I can't find how to compare the values of the minIget column with the columns T1, T2 and T3 and that it returns the name of the column with which the values match.

1 Like

You can just use if_else() or case_when().

mutate(
  whichcol = case_when(
    minIget == T1 ~ "T1",
    minIget == T2 ~ "T2",
    minIget == T3 ~ "T3")
)

This version also handles ties:

mutate(
  whichcol = paste(
    if_else(minIget == T1, "T1", ""),
    if_else(minIget == T2, "T2", ""),
    if_else(minIget == T3, "T3", "")
  )
)
1 Like

Omg! I was already desperate, you helped me a lot although it was something very simple

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.