[R] A better way to Rank Data that considers "ties"

(Ted Harding) Ted.Harding at manchester.ac.uk
Fri Jan 8 22:53:24 CET 2010


On 08-Jan-10 21:09:08, MRKidd wrote:
> This will start off sounding very easy, but I think it will be
> very complicated.
> 
> Let's say that I have a matrix, which shows the number of apples
> that each person in a group has.
> 
> OriginalMatrix<-matrix(c(2,3,5,4,6),nrow=5,ncol=1,byrow=T,
>   dimnames=list(c("Bob","Frank","Joe","Jim","David"),c("Apples")))
> 
>         Apples
> Bob       2
> Frank     3
> Joe       5
> Jim       4
> David     6
> 
> I want to add a third column that shows what each person's rank is
> - e.g. David is number 1 because he has the most apples. 
> 
> So this is what I want:
>          Apples    Rank
> Bob       2          5
> Frank     3          4
> Joe       5           2
> Jim       4           3
> David    6           1
> 
> I have managed to do this in the following steps:
> Unranked<-rownames(OriginalMatrix)
> Ranked<-names(sort(OriginalMatrix,decreasing=T))
> Matched<-match(Unranked,Ranked)
> NewMatrix<-cbind(OriginalMatrix,Matched)
> 
> This is not acceptable, however, if two people have the same number of
> apples.
> 
> You will get:
> 
> NewMatrix
> 
>        Apples    Rank
> Bob      2          5
> Frank   2          4
> Joe      5          2
> Jim      4          3
> David   6          1
> 
> Does anyone know of a way to make it so that both Bob and Frank
> will be ranked as fourth (i.e.- tied for last place)?

The following is one way of approaching it (given in primitive form):

  x<-matrix(c(2,2,5,4,6),ncol=1)
  rownames(x)<-c("Bob","Frank","Joe","Jim","David")
  x
  #       [,1]
  # Bob      2
  # Frank    2
  # Joe      5
  # Jim      4
  # David    6
    unique(sort(x))
  # [1] 2 4 5 6
  N <- length(x)
  X <- cbind(x,rep(0,N))
  Vals <- unique(sort(x))
  M <- length(Vals)
  for(i in (1:N)){X[X[,1]==Vals[i],2]<-(M+1-i)}
  X
  #       [,1] [,2]
  # Bob      2    4
  # Frank    2    4
  # Joe      5    2
  # Jim      4    3
  # David    6    1

Maybe this helps!
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 08-Jan-10                                       Time: 21:53:21
------------------------------ XFMail ------------------------------



More information about the R-help mailing list