Find Column Name with Minimum Value

I have a dataframe where I am trying to find the column name which holds the minimum value for a row.

ColA ColB ColC ColD (I want a column here which identifies column name with min. value:)
1 2 3 5 answer = ColA
9 2 1 5 answer = ColC
7 2 3 5 answer = ColB
6 2 3 5 answer = ColB
4 2 1 5 answer = ColC

I am using a function:

df$answer <- names(df)[which.min(apply(df,MARGIN=2,min))]

however, this function selects the answer ColA in all cases and does not seem to apply to each row but the entire data frame.

Any R experts who know how to solve this issue?

thank you

You almost had it.

df <- data.frame(ColA = c(1, 9, 7, 6, 4),
                 ColB = c(2, 2, 2, 2, 2),
                 ColC = c(3, 1, 3, 3, 1),
                 ColD = c(5, 5, 5, 5, 5))

df$answer <- names(df)[apply(df, MARGIN = 1, FUN = which.min)]

df
#>   ColA ColB ColC ColD answer
#> 1    1    2    3    5   ColA
#> 2    9    2    1    5   ColC
#> 3    7    2    3    5   ColB
#> 4    6    2    3    5   ColB
#> 5    4    2    1    5   ColC

Created on 2020-11-17 by the reprex package (v0.3.0)

1 Like

awesome, thanks...six months into R and trying to achieve basic competency in the syntax!

1 Like

This topic was automatically closed 21 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.