Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# RE: st: create unique random number variable

 From Nick Cox To "'statalist@hsphsun2.harvard.edu'" Subject RE: st: create unique random number variable Date Tue, 24 Apr 2012 13:37:58 +0100

```Alternatively, go into a corner to do this

clear
set obs 1000
set seed 12345
gen double rnd = runiform()
gen n = _n
sort rnd
keep in 1/150

and then the values of -n- should be -merge-d with your main dataset.

Nick
n.j.cox@durham.ac.uk

-----Original Message-----
From: owner-statalist@hsphsun2.harvard.edu [mailto:owner-statalist@hsphsun2.harvard.edu] On Behalf Of Daniel Feenberg
Sent: 24 April 2012 12:20
To: statalist@hsphsun2.harvard.edu
Subject: Re: st: create unique random number variable

On Tue, 24 Apr 2012, raoul reulen wrote:

> Hello
>
> I'm trying to generate a random number variable like this:
>
> .set seed 12345
> .gen x = int(1000*uniform())
>
> However, the random numbers in variable x are not unique. Is there a
> way to ensure they are unique?

The results from uniform are likely to be unique for any reasonably
sized dataset, but rounding to integer will leave you with duplicates
even for relatively small numbers of observations. You could create a
list of unique random integers with by dropping duplicates:

set obs 150
gen x = int(1000*uniform())
duplicates tag x,generate(tag)
keep if tag==0 & _n <=100
save rints,replace

but to get a 100 results I had to start with many more than that and that
ratio would increase asymtotically as one approached 1000 needed values.
Or one could start with 1000 integers in random order, and just use the
number you needed:

set obs 1000
gen x = uniform()
sort x
keep if _n <100
save rints,replace

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```