1

I have a dataframe like this:

 V1      V2     V3    
 0.4    -0.9    0.6
 0.8    -0.2    0.4
-0.6     0.1    0.8

I want to get the maximum value (sign doesn't matter) and print the name of the column with the highest value in a column in the end.

I want to have this:

 V1      V2     V3     MAX 
 0.4    -0.9    0.6    V2
 0.8    -0.2    0.4    V1
-0.6     0.1    0.8    V3

Any ideas?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Mr.Spock
  • 511
  • 2
  • 13

1 Answers1

4

We can use max.col on absolute values of dataframe.

df$MAX <- names(df)[max.col(abs(df))]

df
#    V1   V2  V3 MAX
#1  0.4 -0.9 0.6  V2
#2  0.8 -0.2 0.4  V1
#3 -0.6  0.1 0.8  V3

Similarly we can also use an apply solution row-wise to get maximum value from each row

names(df)[apply(abs(df), 1, which.max)]
#[1] "V2" "V1" "V3"

data

df <- structure(list(V1 = c(0.4, 0.8, -0.6), V2 = c(-0.9, -0.2, 0.1
), V3 = c(0.6, 0.4, 0.8)), class = "data.frame", row.names = c(NA, 
-3L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213