Stata: How to select a random number from a list.

Standard

I want to randomly select a single value of a variable in Stata in order to e.g. delete it in a simulation/bootstrap.

Stata offers simple ways of creating subsamples from a dataset using:

With replacement use:

bsample

Without replacement:

sample

However, it seems a bit more involved to get a random selection from a list of numbersĀ not in the dataset.

This is what I tried to pick a number from a list of numbers at random – undoubtedly to cumbersome.

1) Create a list of random numbers, which is has as many entries as the list you want to select from

foreach num of local listtoselectfrom { 
 local randomnumber = runiform()
 local rnumbers = "`rnumbers'`randomnumber' "
}

2) Sort the list of random numbers

local selection : list sort renumbers

3) Select the lowest random number

local posofselected = word("`selection'",1)

4) Find the position of this lowest random number in the unsorted list of random numbers

local posinselectionlocal : list posof "`posofselected'" in rnumbers 

5) Use this position to select at random ONE item from the list you want to select from:

local randomitem : word `posinselectionlocal' of `listtoselectfrom'

Example

set seed 7492001 //For replicability.

local listtoselectfrom = " 1 3 4 5 9 10"

foreach num of local listtoselectfrom { 
	local randomnumber = runiform()
	local rnumbers = "`rnumbers'`randomnumber' "
}
local selection : list sort rnumbers
local posofselected = word("`selection'",wordcount("`selection'")) 
local posinselectionlocal : list posof "`posofselected'" in rnumbers 
local randomitem : word `posinselectionlocal' of `listtoselectfrom'
dis "This is the selected number: `randomitem'"

P.S. More than one number
The select more than one number, select more numbers from the random number list in 3). And change loop over their positions using step 4) and 5).

Reference:
The described procedure was inspired by following two posts:
1) http://whatthestats.wordpress.com/2012/08/07/stata-selecting-random-samples/

2) http://blog.stata.com/2012/07/18/using-statas-random-number-generators-part-1/