2

Input data

soo<-structure(list(Mycol1 = c(11.9, 7.8, 8.2, 14.7, 1, 21.7, 0, 48.6, 
0, 2.8), Mycol2 = c(10.2, 2.7, 6.4, 55.1, 1, 8.6, 0, 0, 0, 1.9
)), row.names = c(NA, 10L), class = "data.frame")

Aim

I would like to extract the name of the column with the maximum value for each row.

Attempt

I can get the maximum value, but how do I get the name of the column that it is in.

do.call(pmin, c(soo, na.rm = TRUE))
Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125
  • Do you want to calculate row-wise maximum or minimum? Your title and body text do not match. Can you correct it? – Ronak Shah Aug 18 '19 at 09:31

2 Answers2

5

You can do it like:

soo$max_col = colnames(soo)[apply(soo, 1, which.max)]

Output:

   Mycol1 Mycol2 max_col
1    11.9   10.2  Mycol1
2     7.8    2.7  Mycol1
3     8.2    6.4  Mycol1
4    14.7   55.1  Mycol2
5     1.0    1.0  Mycol1
6    21.7    8.6  Mycol1
7     0.0    0.0  Mycol1
8    48.6    0.0  Mycol1
9     0.0    0.0  Mycol1
10    2.8    1.9  Mycol1
Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73
3

We can use max.col which will return column number with max value in each row and to handle NAs we can replace them with 0. We use ties.method = "first" so in case if we have a tie in a row for max value we select the first max always.

soo$max_col <- names(soo)[max.col(replace(soo, is.na(soo),0),ties.method = "first")]

soo
#   Mycol1 Mycol2 max_col
#1    11.9   10.2  Mycol1
#2     7.8    2.7  Mycol1
#3     8.2    6.4  Mycol1
#4    14.7   55.1  Mycol2
#5     1.0    1.0  Mycol1
#6    21.7    8.6  Mycol1
#7     0.0    0.0  Mycol1
#8    48.6    0.0  Mycol1
#9     0.0    0.0  Mycol1
#10    2.8    1.9  Mycol1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213