Oscar Kjell
Oscar Kjell

Reputation: 1651

For each row, return the column name of the largest value whilst removing ties

I have this data:

x = c(1,1,3, 3, 2)
y = c(1,2,1, 1, 2)
z = c(1,1,2, 3, 7)

data <- data.frame(x, y, z)

And I would like to get a vector indicating the column number of the highest value in each row; whilst removing ties; or indicate ties with NA.

I have tried which.max:

HighestIncludingTies <- apply(data, 1, which.max)

Although this does not mark ties with NA (or something similar).

Thanks a lot for any help or guidance!

Upvotes: 3

Views: 350

Answers (1)

thelatemail
thelatemail

Reputation: 93843

Here's an attempt using max.col:

HighsNoTies <- max.col(data,"first")
replace(HighsNoTies, HighsNoTies != max.col(data,"last"), NA)
#[1] NA  2  1 NA  3

Upvotes: 6

Related Questions