1

I have a data frame with repeating IDs and different values, what I want to do is rank each value within it respective ID

 test <- data.frame(ID = c("A", "B", "C","A", "B", "C","A", "B", "C"), Value = c(15,1,5,17,3,1,19,2,2))

  ID Value
1  A    15
2  B     1
3  C     5
4  A    17
5  B     3
6  C     1
7  A    19
8  B     2
9  C     2

I can sort them but I can't figure out how to assign the rank values.

test[order(test$ID, test$Value, decreasing = T),]
  ID Value
3  C     5
9  C     2
6  C     1
5  B     3
8  B     2
2  B     1
7  A    19
4  A    17
1  A    15

Desired output would be

  ID Value Rank 
3  C     5    1
9  C     2    2
6  C     1    3
5  B     3    1
8  B     2    2
2  B     1    3
7  A    19    1
4  A    17    2
1  A    15    3
Cœur
  • 37,241
  • 25
  • 195
  • 267
George
  • 903
  • 8
  • 22
  • With `test2 = test[order(test$ID, test$Value, decreasing = T),]`, you can do `with(test2, ave(ID, ID, FUN = seq_along))` – Frank Mar 14 '17 at 21:35
  • @Frank Thank you, ID is a factor and that appears to cause an issue with your code, if I change the class to character then it seems to work. – George Mar 14 '17 at 21:47
  • 1
    Ah, ok, that's because of weird `ave` behavior I forgot about. `with(test2, ave(Value, ID, FUN = seq_along))` is another way to get around it, besides the conversion you mention. The weird behavior is: `ave` will always return a result that has the same class as its first argument. Personally, I would only use data.table or dplyr for this (as covered in the link above). – Frank Mar 14 '17 at 21:53

0 Answers0