Ernest Berkhout
>
> i was looking for a way to cycle through all the values of
> a particular
> variable 'oplnr' without having to hardcode these values
> (they changes
> every year). Walking through some faqs I come across the
> program 'vallist'
> which should be able to do this for me. I integrated this in a small
> foreach-loop program, but I get an errormessage that does
> not make sense to
> me. As I'm not very experienced in programming Stata, it
> might be some
> silly typo which I overlooked, but I cant see what is is.
> Or is there maybe
> some other problem unknown to me?
>
> The basic idea is to create a set of dummy-variables for
> interactions
> between to variables oplnr & brinnr. But not all combinations are
> meaningful in practice, so for reason of efficiency I want
> to drop all
> dummies that indicate 'empty cells', that is for which all
> records have a
> zero-value.
> The program stores the values of a variable 'oplnr' in some
> macro `oplnr',
> and then I introduce another loop which should cycle
> through a second set
> of values (1 to 13) stored in the macro `brinnr'.
> The following is the code that I've written:
> ******************************
> gen temp=.
> vallist oplnr
> foreach oplnr of local r(list) {
> forvalues brinnr = 1/13 {
> gen byte opXbr_`oplnr'_`brinnr' = (oplnr==`oplnr' &
> brinkort==`brinnr')
> qui summ opXbr_`oplnr'_`brinnr', meanonly
> replace temp=r(max)
> if temp==0 drop opXbr_`oplnr'_`brinnr'
> }
> }
> drop temp
> ********************************************
>
> The error message I get is:
>
> { required
> r(100)
>
> Can someone please hint me what is wrong in my code? I do
> have 2 opening
> and 2 closing brackets, why does that produce such an error?
r(list) is not the name of a local macro. That's
what -foreach- is expecting after the keyword -local-.
Stata doesn't give you a very appropriate error message,
but that is because it is confused.
My advice is to junk -vallist- and use -levels- instead
from SSC. -vallist- is a poor program compared with -levels-,
and the authors agree on that without rancour.
Turning to your code, you don't need -temp-:
levels oplnr, local(levels)
foreach l of local levels {
forvalues b = 1/13 {
gen byte opXbr_`l'_`b' = (oplnr==`l' & brinkort==`b')
summ opXbr_`l'_`b', meanonly
if r(max) == 0 drop opXbr_`l'_`b'
}
}
and you can make the -generate- conditional on there being
some true values, rather than doing a -generate- and then
a conditional -drop-.
levels oplnr, local(levels)
foreach l of local levels {
forvalues b = 1/13 {
capture assert (oplnr==`l' & brinkort==`b') == 0
if _rc gen byte opXbr_`l'_`b' = (oplnr==`l' & brinkort==`b')
}
}
Nick
[email protected]
*
* 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/