raynach
raynach

Reputation: 597

Select max or equal value from several columns in a data frame

I'm trying to select the column with the highest value for each row in a data.frame. So for instance, the data is set up as such.

> df <- data.frame(one = c(0:6), two = c(6:0))
> df
  one two 
1   0   6
2   1   5
3   2   4
4   3   3
5   4   2
6   5   1
7   6   0

Then I'd like to set another column based on those rows. The data frame would look like this.

> df
  one two rank 
1   0   6    2
2   1   5    2
3   2   4    2
4   3   3    3
5   4   2    1
6   5   1    1
7   6   0    1

I imagine there is some sort of way that I can use plyr or sapply here but it's eluding me at the moment.

Upvotes: 1

Views: 2917

Answers (1)

Hilary Parker
Hilary Parker

Reputation: 66

There might be a more efficient solution, but

ranks <- apply(df, 1, which.max)
ranks[which(df[, 1] == df[, 2])] <- 3

edit: properly spaced!

Upvotes: 5

Related Questions