-2

I have written an R function that takes a vector as input and returns as output another vector so that the minimum of the input vector is replaced by 1, the element that is greater than the minimum is replaced by 2 etc until the maximum of the vector, which is replaced by the length of the vector. This is my function:

  resc<-function(x){
   m<-length(unique(x))
   nor<-rep(0,length(x))
   x_2<-x
   for(i in 1:m){
     temp<-min(x_2)
     temp_2<-which(x==temp)
     nor[temp_2]<-i
     x_2<-x_2[-which(x_2==temp)]
   }
   return(nor)
 }

How can I rewrite this function in Python? I tried, but I was a bit confused with the use of command 'which'.

  • 4
    For what it's worth, that function already exists in R and it's `rank`. Don't know python enough to tell how to translate that. – nicola Dec 05 '16 at 10:37
  • 1
    For R, you can use `rank` which gives you the rank of that element in the vector and for python maybe [Rank items in an array using Python/NumPy](http://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy) – Ronak Shah Dec 05 '16 at 10:39
  • 1
    Thank you both for the intuition in the R language @nicola and @Ronak! I think this is what i am looking for! – Leonidas Souliotis Dec 05 '16 at 10:41
  • python built in functions: https://docs.python.org/2/library/functions.html –  Dec 05 '16 at 14:14

1 Answers1

1

As Ronak and Nicola said, all you need is the rank function to get the same result.

In Python, I would try:

import scipy.stats as ss
ss.rankdata([array])
Sonny
  • 3,083
  • 1
  • 11
  • 19