# Re: st: -generate- and run time contingencies

 From n j cox To statalist@hsphsun2.harvard.edu Subject Re: st: -generate- and run time contingencies Date Mon, 30 Jan 2006 16:09:18 +0000

```I am wary of offering generic comments, because
I don't have a good sense of the generic problem.
Mike's specific problem is clear, but there is
an obvious work-around, as he says, which at least
this Stata programmer would prefer. So, can
you give a _second_ problem example? Beyond that,
using Mata is recommended these days rather
than the old-style code you use.

Finally, the try-and-try-again technique
is not guaranteed to end in finite time,
but it doesn't need to be recast as
a matrix problem. It would be interesting
to know what is faster.

// not tested
gen x = uniform()
gen byte OK = x >= 0.8
capture assert OK == 1

while _rc {
replace x = cond(x < 0.8, uniform(), x)
replace OK = x >= 0.8
capture assert OK == 1
}

Nick
n.j.cox@durham.ac.uk

Mike Lacy

One feature of Stata with which I continue to experience difficulty
concerns how to assign a value to a variable based on a run time
contingency. As a simple illustration, consider the goal of assigning
a uniform r.v. value to a variable, while rejecting values less than,
say, 0.8.  If  -while- was sensitive to run time values of variables,
I would do:

gen x = uniform()
while (x < 0.8) {
replace x = uniform()
}

Obviously, this construct that would work in many languages does not
work as desired in Stata, and just as obviously, there are other ways
to accomplish the same end in Stata [  gen x = 0.8 + 0.2*uniform() ].

My question, then, concerns a general approach to these run-time
contingencies, not all of which suggest simple workarounds to me.
What seems most straightforward but clumsy as a generic approach is
to do the code fragment involving the contingency as a matrix
operation, and then save it back to a variable, e.g.,

matrix X = J(_N, 1, .)
local top = rowsof(X)
forvalues i = 1/`top'{
scalar temp = uniform()
while temp < 0.8 {
scalar temp = uniform()
}
matrix X[`i',1] = temp
}
svmat X, name(MyVarName)

Any generic suggestions here?

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```