Hi everyone,
I kindly need some help on looping and exporting results to excel.
I want to produce one-way tables for several variables and export the results to excel. I used the codes below from existing advice on Statalist. It works fine. But, I want to produce the one-way tables involving several variables across regions. In my data, I have a variable called "region" with 31 labelled values. I want to produce one-way tables for the five variables I have (PrBefore2013 SecBefore2013 PrCurrent Trendexist Currentfood) based on the "region" variable that has 31 regional indicators (labels). That is, I want to produce 31 one way tables for the each of the 5 variables of interest, and export the results to excel.
Thank you for your time and help.
I kindly need some help on looping and exporting results to excel.
I want to produce one-way tables for several variables and export the results to excel. I used the codes below from existing advice on Statalist. It works fine. But, I want to produce the one-way tables involving several variables across regions. In my data, I have a variable called "region" with 31 labelled values. I want to produce one-way tables for the five variables I have (PrBefore2013 SecBefore2013 PrCurrent Trendexist Currentfood) based on the "region" variable that has 31 regional indicators (labels). That is, I want to produce 31 one way tables for the each of the 5 variables of interest, and export the results to excel.
Code:
local yvars "PrBefore2013 SecBefore2013 PrCurrent Trendexist Currentfood" qui foreach var of local yvars { loc row = 2 putexcel set "$Table/Incomesources.xlsx", sheet ("`var'") modify tab `var', matcell(freq) matrow(rname) loc rows = rowsof(rname) forval i = 1/`rows' { loc val = rname[`i', 1] loc val_lab : lab `var' `val' loc rfreq = freq[`i', 1] loc total = r(N) loc percent : di %4.2f (`rfreq'/`total')*100 putexcel A1=("Category") B1=("Levels") C1=("Freq") D1=("Percent") putexcel A`row' = "`:var lab `var''" putexcel B`row' = `val_lab' putexcel C`row' = `rfreq' putexcel D`row' = `percent' loc ++row } }