Predictive Hacks

How to get the Column of the Max Value by Row

Assume that our data frame is:

set.seed(5)
df<-as.data.frame(matrix(sample(1:100,12),ncol=3))
df
  V1 V2 V3
1 66 41 19
2 57 85  3
3 79 94 38
4 75 71 58

We can get the index and the name of the max column by row as follows:

colnames(df)[max.col(df,ties.method="random")]
[1] "V1" "V2" "V2" "V1"

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.