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   Daniel Feenberg <>
Subject   Re: st: create unique random number variable
Date   Tue, 24 Apr 2012 07:20:09 -0400 (EDT)

On Tue, 24 Apr 2012, raoul reulen wrote:


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

Daniel Feenberg


*   For searches and help try:

*   For searches and help try:

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