[R] repeat until function

Philipp Pagel p.pagel at gsf.de
Wed Nov 12 16:16:36 CET 2003


> I what to generate N random numbers(integer) that are different from each 
> other.
> One suggestion:
> 
> tabel <- rep(NULL, N)
> for (i in 1:N){
>   temp <- as.integer(runif(1,1,max))
>   if(temp in tabel) {
>       repeat (?) (temp <- as.integer(runif(i,i,max)))
>       until (?) ((temp in tabel) ==FALSE)
>   }
>   else{ tabel[i] <- temp}
> 
> I can't use repeat/until - don't exist....

repeat ... until loops can be rewritten as while loops.


The easiest way is this:

# n unique random numbers between min and max
sample(min:max, n)


But maybe you don't want to generate the array min:max for some reason
(because it is really large?). Then you can do the whole thing yourself:

# another way to the same result
left <- n
tab <- NULL
while (left > 0) {
	new <- as.integer(runif(left, min, max))
	tab <- unique(c(tab, new))
	left <- n - length(tab)	
}

If max-min is really large and n is not much smaller than max-min you
may want to generate more numbers than you actually need so unique()
leaves you with more results and you don't have to iterate so often...

cu
	Philipp

-- 
Dr. Philipp Pagel                                Tel.  +49-89-3187-3675
Institute for Bioinformatics / MIPS              Fax.  +49-89-3187-3585
GSF - National Research Center for Environment and Health
Ingolstaedter Landstrasse 1
85764 Neuherberg, Germany




More information about the R-help mailing list