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]

st: Re: select three non-identical random elements


From   "Joseph Coveney" <stajc2@gmail.com>
To   <statalist@hsphsun2.harvard.edu>
Subject   st: Re: select three non-identical random elements
Date   Thu, 4 Apr 2013 21:09:07 +0900

Tomáš Houška wrote:

I have list of items create by -levelsof- macro and I would like to select
three items from that list at random and for them to be non-repetitive
(i.e. each one can appear only once in the selection).

Lets say I have a list -local list "one two three four five six"- and I
would like to get
local random1 =
local random2 =
local random3 =

where each one is a random selection from the local list and each item
appears at max once.
I would appreciate any help on how to do that.

--------------------------------------------------------------------------------

Macro extended functions for manipulating lists (-help macrolists-) will help
you to randomly sample without replacement from a local macro containing a list
of words.  

As Nick mentions, there might be better ways in the long run using Mata, but
this should get you going until then.

Joseph Coveney

. 
. local word_list one two three four five six

. 
. local want 3

. 
. set seed `=date("2013-04-03", "YMD")'

. 
. local words : word count `word_list'

. assert `want' <= `words'

. 
. local loop 1

. while `loop' <= `want' {
  2.         local randu = 1 + floor((`words' - 1) * runiform())
  3.         local random`loop' : word `randu' of `word_list'
  4.         local word_list : list word_list - random`loop'
  5.         local --words
  6.         local ++loop
  7. }

. 
. display "`random1'"
five

. display "`random2'"
one

. display "`random3'"
four


*
*   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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index