0

I have a table in R that looks like this:

ID | Var1 | Var2 | Var3
1  | 0.2  | 0.5  | 0.3
2  | 0.6  | 0.4  | 0.0
3  | 0.1  | 0.4  | 0.5

I want to know for each ID which Var has the highest value. Thus, the final table should look like this:

ID | Var1 | Var2 | Var3 | HighVar
1  | 0.2  | 0.5  | 0.3  | Var2
2  | 0.6  | 0.4  | 0.0  | Var1
3  | 0.1  | 0.4  | 0.5  | Var3

How do I achieve this in R?

jkortner
  • 549
  • 2
  • 8
  • 23

1 Answers1

0

We can use max.col in base R

df$HighVar <- names(df)[-1][max.col(df[-1], 'first')]

data

df <- data.frame(ID = 1:3, Var1 = c(0.2, 0.6, 0.1), 
      Var2 = c(0.5, 0.4, 0.4), Var3 = c(0.3, 0, 0.5))
akrun
  • 874,273
  • 37
  • 540
  • 662