0

I'm looking to find a solution here that would decide between 3-4 columns on a line-by-line basis (apply?), and allocate the name of highest value column in a new column [df$NAME]. Below is what I'd like the result to look like; what is the best approach for this? Thank you!

| Bird | Cat | Dog |  NAME
| 3    |  4  |  10 |   DOG 
| 5    |  2  |   4 |   BIRD
| 3    |  6  |   2 |   CAT
| 4    |  8  |   9 |   DOG

1 Answers1

0

Is there something like a pmax index? is perfect for you.

The max.col()-based solution (second answer in the linked question) is preferable to the apply()-based solution, both for simplicity and efficiency.

df$NAME <- names(df)[max.col(df)];
df;
##   Bird Cat Dog NAME
## 1    3   4  10  Dog
## 2    5   2   4 Bird
## 3    3   6   2  Cat
## 4    4   8   9  Dog

Data

df <- data.frame(Bird=c(3L,5L,3L,4L),Cat=c(4L,2L,6L,8L),Dog=c(10L,4L,2L,9L));
Community
  • 1
  • 1
bgoldst
  • 34,190
  • 6
  • 38
  • 64