Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.


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

Re: st: create unique random number variable


From   Daniel Feenberg <feenberg@nber.org>
To   statalist@hsphsun2.harvard.edu
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:

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

Daniel Feenberg




Thanks!

Raoul
*
*   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/

*
*   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/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index