foreach var in Punjab age_cat Division District2 {
preserve
collapse (count) n_sex_total (mean)sex_total (count) n_total_sex_m (mean) percent_sex_m (mean) total_sex_m (count) n_sex_f (mean) sex_f ///
if total_n==1, by(`var')
decode `var', gen(backgound)
drop `var'
drop if backgound==""

order background n_sex_total sex_total n_total_sex_m percent_sex_m total_sex_m n_sex_f sex_f
save "$table/`var'.dta", replace
restore
}
*
use "$table/punjab.dta", clear
erase "$table/punjab.dta"
foreach var in age_cat Division District2 {
append using "$table/`var'.dta"
erase "$table/`var'.dta"
}
*
export excel using "$table/Total_population3.xls", firstrow(variables) replace
save "$table/Total_population3.dta", replace


n_sex_total is the total population and sex_total is the total population in 100 0 form for the calculation of mean n_total_sex_m is the total males population percent_sex_m is the males population in 100 0 form for the calculation of mean of males population in any category to total males while total_sex_m is in 100 0 form to calculate mean of total males population to total population and n_sex_f is the total female population and sex_f is in 100 0 form to calculate mean of sex_f with respect to total population. but this loop is not giving me the desired results as it is giving me 100 percentage when i calculate percent_sex_m and sex_f. kindly any suggestion for improvement of this loop so that i can find my desired results.