Bookmark and Share

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


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

Re: st: generating random numbers without replacement


From   Nick Cox <[email protected]>
To   "[email protected]" <[email protected]>
Subject   Re: st: generating random numbers without replacement
Date   Sat, 25 May 2013 06:05:45 +0100

Note that the Mata code misses a trick

a = J(100,1,.)
for(i = 1; i<=100; i++) a[i,1] = i

is a long-winded alternative to

a = 1::100

In fact you could shorten the code further, but I will stop there.

One Stata translation is

set obs 100
gen a = _n
gen rnd = runiform()
sort rnd
l a rnd

I would usually preface that by -set seed 2803- or some such.

Here is a line-by-line translation

mata
// open Mata
a=J(100,1,.)
// a is a vector with 100 rows, 1 column, all missing values
for(i=1;i<=100;i++) a[i,1]=i
// loop from i = 1 to i = 100 incrementing i by 1 at each step:
// set the i th row and 1st column of a to i
a=a,runiform(100,1)
// join a row-by-row with a vector with 100 rows, 1 column of uniform
random numbers
a=sort(a,2)
// sort a according to the values in the second column:
// wanted consequence is a random shuffle of 1::100 in first column
a
// now show me a

I wrote -swor- a while back, but I can't remember much about it. More
important is -sample-.

SJ-5-1  dm86_1  . . . . . . . . . . . . . . . . . . . Software update for swor
        (help swor if installed)  . . . . . . . . . . . . . . . . .  N. J. Cox
        Q1/05   SJ 5(1):139
        swor rewritten to use sort, stable for reproducibility and
        sortpreserve for compatibility; help file also modernized

STB-59  dm86  Sampling without replacement: abs. sample sizes & keeping all obs
        (help swor if installed)  . . . . . . . . . . . . . . . . .  N. J. Cox
        1/01    pp.8--9; STB Reprints Vol 10, pp.38--39
        samples without replacement a specified sample size;
        alternative to sample

Nick
[email protected]

On 24 May 2013 22:30, Michael McCulloch <[email protected]> wrote:

> I wish to generate random numbers between 1 and 5, without replacement. I have located the following Mata code, but have not yet learned Mata. Is it possible to rewrite this to create the variable a?
>
> mata
> a=J(100,1,.)
> for(i=1;i<=100;i++) a[i,1]=i
> a=a,runiform(100,1)
> a=sort(a,2)
> a
> end
>
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


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