You were almost there with return macro var r(r). This will
evaluate to the number of categories of your tabulated variable.
Just add that to your code:
. local varlist_2 = "verbal_sat dum1-dum`r(r)'"
. di "`varlist_2'"
verbal_sat dum1-dum30
Dan Blanchette
Carolina Population Center UNC-CH
>
> Dear Statalist members,
>
> I met a small stata problem. Does anyone have a good way to do it?
>
> Problem:
>
> The subprogram is like this:
>
> load big data set
> select small data set
> generate dum
> show how many dum variables are generated
> loop to operate on each dum
>
> In total, there are over fifty such small subprograms, every small data set is different from the other.
>
> I have to check how many dums are there in the subprogram and put the number into loop. Everytime, I change the big dataset, I have to recheck the dum number and reinput the dum number into the loop.
>
> How can I let the stata do this automatically?
>
> Example of subprogram:
>
> use pdp_matching.dta, clear
>
> keep gender coalition_pool verbal_sat math_sat c32_lecture c32_times_taken c32_year c32_term c32_num_grade c32_math_98 c32_pdp_ids c32_pdp_ids_not_pass c32_slc_adjunct c32_slc_adjunct_not_pass
>
> drop if gender == .
> drop if coalition_pool == .
> drop if verbal_sat == .
> drop if math_sat == .
> drop if c32_lecture == .
> drop if c32_year == .
> drop if c32_term == .
> drop if c32_num_grade == .
>
> keep if c32_num_grade < 5
>
> generate same_class = c32_year*100 + c32_term*10 + c32_lecture
>
> tabulate same_class, gen(dum)
>
> di r(r)
>
> local varlist_1 = "gender math_sat"
> local varlist_2 = "verbal_sat dum1-dum30"
>
> Note: I have to input 30 by myself before!!! Can stata do this automatically?
>
> foreach var of local varlist_1 {
> egen `var'_max = max(`var')
> egen `var'_min = min(`var')
> if `var'_max ~= `var'_min {
>
> local varlist_2 = "`varlist_2' `var'"
> di "keep `var'"
> }
> else {
> display "drop `var'"
>
> }
> }
> display "Finish dropping"
>
>
>
> Warm regards,
>
> Maoyong Fan
>
>
>
>
>
>
*
* 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/