-2

I have the following data:

df
     dc1  dc2  dc3   min_colname
[1,] 12.9 13.4 13.4
[2,]  6.1  6.5  6.5
[3,]  6.3  6.7  6.7
[4,] 21.0 21.4 21.4
[5,]  1.6  1.8  1.8
[6,]  3.3  3.7  3.7
[7,]  7.0  7.4  7.4
[8,]  3.2  3.6  3.6
[9,] 14.8 15.2 15.2
[10,]  7.9  8.3  8.3

I am trying to add one more column say min_colname which will have the min values of each row but mapped to column name....for example for row 1 min value is 12.9..so the first item in min_colname should be dc1 and not the actual obs value.....

Nishant
  • 1,063
  • 13
  • 40
  • 1
    `colnames(df)[max.col(-df, "first")]` - pretty sure this is a duplicate – thelatemail Dec 06 '16 at 05:22
  • 1
    Possible duplicate of [for each row, return the column name of the largest value](http://stackoverflow.com/questions/17735859/for-each-row-return-the-column-name-of-the-largest-value) Or [R return the index of the minimum column for each row](http://stackoverflow.com/questions/18324053/r-return-the-index-of-the-minimum-column-for-each-row) – Ronak Shah Dec 06 '16 at 05:26
  • You can tweak the answers in these links a little to get your required output. – Ronak Shah Dec 06 '16 at 05:28

1 Answers1

0

This should work:

df$min_colname  <- apply(df, 1, function(x) colnames(df)[which.min(x)])
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63