Bookmark and Share

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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: st: create unique random number variable

From   Nick Cox <>
To   "''" <>
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 

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. 


-----Original Message-----
From: [] On Behalf Of Daniel Feenberg
Sent: 24 April 2012 12:20
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:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index