[R] how to sort random numbers according to the sample ?

Dimitrios Rizopoulos Dimitris.Rizopoulos at med.kuleuven.be
Sun Dec 10 12:01:19 CET 2006


in your example you need

r <- matrix(runif(12), 4, 3)
x <- c(6, 8, 9, 11)
########
apply(r, 2, function(y) x[order(y)])


however, you can directly use sample(), i.e.,

sapply(1:3, function(i) sample(x))


I hope it helps.

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
      http://www.student.kuleuven.be/~m0390867/dimitris.htm


Quoting Jenny persson <jenny197806 at yahoo.se>:

> Dear R-users,
>
>   ####  below is my code to randomized x three times.
>
>   > x=c(6,8,9,11)
>> plan=NULL
>> for(i in 1:3){
> + set.seed(i)
> + r<-runif(x)
> + plan=cbind(plan,r)
> + }
>
>
>
>   #####  which gave the matrix
>
>   > plan
>              r                  r         r
> [1,] 0.2655087 0.1848823 0.1680415
> [2,] 0.3721239 0.7023740 0.8075164
> [3,] 0.5728534 0.5733263 0.3849424
> [4,] 0.9082078 0.1680519 0.3277343
>
>   #### and order numbers
>
>>  apply(plan,2,order)
>        r r r
> [1,] 1 4 1
> [2,] 2 1 4
> [3,] 3 3 3
> [4,] 4 2 2
>
>   ### My question is, is there a way to order the matrix "plan"   
> according to x so I don't have to check that 1 is corresponding to   
> 6, 2 corresponds to 8 , 3 to 9 and 4 to 11. I mean after ordering   
> matrix "plan " the result should be
>
>        r   r     r
> [1,] 6   11   6
> [2,] 8   6   11
> [3,] 9   9     9
> [4,] 11 8     8
>
>   Thanks for any help,
>
>   All the bests,
>   Jenny
>
>
> ---------------------------------
>
> Stava rätt! Stava lätt! Yahoo! Mails stavkontroll tar hand om   
> tryckfelen och mycket mer! Få den på http://se.mail.yahoo.com
> 	[[alternative HTML version deleted]]
>
>



Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm




More information about the R-help mailing list