Alan
Alan

Reputation: 681

Identifying Column With Highest Numeric Value in Data Frame in R

I've got a data frame with a large number of columns. Each is numeric.

For each row of data I'd like to know which column has the highest number in it.

Very simple example:

x <- data.frame(score1 = c(10, 12, 25),
                score2 = c(9, 13, 20),
                score3 = c(14, 8, 8))

For row 1, score3 is highest.

For row 2, score2 is highest.

For row 3, score1 is highest.

So I'd like something that outputs:

max_score_col_name <- c("score3", "score2", "score1")

Is there an easy way to do this please?

(I've ignored the tricky question of what happens if there's a tie for the lead because the data is in a form such that this won't happen)

Upvotes: 1

Views: 63

Answers (2)

lonelyLearner
lonelyLearner

Reputation: 41

another option:

colnames(x)[apply(x, 1, which.max)]

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 39858

One option could be:

names(x)[max.col(x)]

[1] "score3" "score2" "score1"

Upvotes: 4

Related Questions