[R] How to rank vectors based on their elements?

Petr Savicky savicky at cs.cas.cz
Sun Apr 15 13:52:30 CEST 2012


On Sun, Apr 15, 2012 at 02:52:11AM -0700, Manish Gupta wrote:
> Hi,
> 
> 
> In my case, your first guess is right.  I need to rank classes based on
> their feature vector.
> 
>    1   3   4  -2   0  class1 
>    2   0   0  -3   0  class2 
>    2   3   1   4   5  class3 
>   -4  -5   1   0   0  class4 
> 
> Like class1 > class3> class4> class2
> 
> How can i implement it?

Hi.

The ordering may be defined in many ways depending on the purpose
of the ordering. Since i do not know this purpose, i can only
guess, what can be meaningful. Try the ordering by the mean
value. This can be done as follows.

  class1<-c(1,3,4,-2,0)
  class2<-c(2,0,0,-3,0)
  class3<-c(2,3,1,4,5)
  class4<-c(-4,-5,1,0,0)
  mat <- rbind(class1, class2, class3, class4)
  mat[order(rowMeans(mat), decreasing=TRUE), ]

         [,1] [,2] [,3] [,4] [,5]
  class3    2    3    1    4    5
  class1    1    3    4   -2    0
  class2    2    0    0   -3    0
  class4   -4   -5    1    0    0

If the importance of the features is not equal, one can use
weigted mean. For example, as follows.

  w <- c(1, 1, 4, 1, 1)
  weightedMean <- (mat %*% w)/sum(w)
  mat[order(weightedMean, decreasing=TRUE), ]

         [,1] [,2] [,3] [,4] [,5]
  class1    1    3    4   -2    0
  class3    2    3    1    4    5
  class2    2    0    0   -3    0
  class4   -4   -5    1    0    0

Hope this helps.

Petr Savicky.



More information about the R-help mailing list