Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: forvalues problem


From   Fred Wolfe <[email protected]>
To   [email protected]
Subject   st: forvalues problem
Date   Thu, 01 Aug 2002 05:09:06 -0500

As a further clarification of the macro problem, here is some test code:

I am trying to create a series of macros for each catagorical `var' at each level of the category.

foreach var of varlist `varlist' {
if index("`catvar'", "`var'") != 0 | index("`mcatvar'", "`var'") != 0 {
local catvarnum = `catvarnum' + 1
global catvar`catvarnum' `var'
di "This categorical variable is number `catvarnum'"
tempname Vals Cell
if index("`catvar'", "`var'") != 0 {
qui tab `var', matrow(`Vals') matcell(`Cell')
local nvals = r(r)
local valtot = r(N)
}
else { qui tab `var', matrow(`Vals') matcell(`Cell') miss
local nvals = r(r)
local valtot = r(N)
}

di "`var'"
forvalues i = 1 / `nvals' {
local val = `Vals'[`i',1]
local count = `Cell'[`i',1]
local vname: label (`var') `val'
local catpct = (`count'/`valtot') * 100
di "`vname' `valtot' ` catpct'"

This works fine up to here.

What I need to do now is make macros for each level of `var' and `i'.
`catvarnum' picks up the `var'
`i' stays as `i'

Originally the plan was to create local macros rather than the global ones shown previously.

global catvar`catvarnum'_vname_`i' `vname'
global catvar`catvarnum'_N_`i' = `count'
global catvar`catvarnum'_Total_`i' = `valtot'
global catvar`catvarnum'_Mean_`i' = `catpct'

global catvar`catvarnum'_totline = `i'
local catvar`catvarnum'_totline = `i'
di "`catvar`catnum'_totline'"
The above line produces the right answers, so the code is OK up to here.

Now, as an example, follow "local catvar`catvarnum'_totline = `i'"
}
di
}
}

forvalues j = 1 / 2 {
forvalues k = 1 / `catvar`j'_totline' {
* forvalues k = 1 / $catvar`j'_totline { <-- invalid syntax error here

however, this gets an "invalid syntax" error.

All of which led me to move to global macros,
No matter how I change the ` ' or add { } or " ", I can't get the local macro to work
*di "`k'. `testvar'"
* di "`k'. ${catvar`j'vname"`k'}"
}
}

Zhiqiang's suggestion works, but it is a little unsatisfying to create an extra level of macros just to get it to work, but perhaps that is the only way.

Fred



---------------------------------------------------------------------------- ------------------------
Fred Wolfe Tel (316) 263-2125
National Data Bank for Rheumatic Diseases Fax (316) 263-0761
Wichita, Kansas [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/




© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index