# [R] quantile

(Ted Harding) Ted.Harding at manchester.ac.uk
Mon Sep 29 23:33:35 CEST 2008

```On 29-Sep-08 20:09:14, liujb wrote:
> Hello,
> I need to assign a number to each x[i], i=1:100, based on the
> value of x[i] and where they are in the distribution of x[i].
> For example 1 for x[4] means x[4] is below 25%. I can obtain
> the quantile using quantile command, and just loop through the
> 1:100 and assign the correct number. But I was just wondering
> whether there are a more efficient way.
>
> Thank you,
> sincerely,
> Julia

Well, you can certainly do it with a much shorter loop!

set.seed(31425)
x   <- rnorm(13)
x.v <- numeric(length(x))
ix  <- order(x)
Q <- quantile(x)
for(i in (5:2)){ x.v[x<=Q[i]] <- (i-1) }

cbind(x,x.v, x[ix],x.v[ix])
x x.v
[1,] -0.7565336   2 -1.7045077 1
[2,] -0.3287683   2 -1.0693801 1
[3,] -1.7045077   1 -1.0671752 1
[4,]  0.7259883   4 -0.9718954 1
[5,]  0.6174724   3 -0.7565336 2
[6,] -1.0693801   1 -0.3668566 2
[7,]  1.9826596   4 -0.3287683 2
[8,] -0.9718954   1  0.2491123 3
[9,] -1.0671752   1  0.4733287 3
[10,] -0.3668566   2  0.6174724 3
[11,]  0.2491123   3  0.7259883 4
[12,]  0.4733287   3  1.9826596 4
[13,]  2.2095536   4  2.2095536 4

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 29-Sep-08                                       Time: 22:33:33
------------------------------ XFMail ------------------------------

```

More information about the R-help mailing list