Hi everyone,

I'm trying to automatize/optimize the code used to create my primary table.
What I'm trying to do is to make a table for each of my explaining variables according to vaccination status (yes/no) with frequencies and percentages for each category and the combine them in a matrix that I will write to an excel file.

If I were to do this individually for each variable this would be the code (here with sex as an example):

Code:
estpost tab vac sex , nototal
matrix freq_sex=e(b)'
matrix perc_sex=e(colpct)'

matrix coljoinbyname freq_perc_sex = freq_sex perc_sex

mata
freq_perc_sex=st_matrix("freq_perc_sex")
freq_perc_sex=colshape(freq_perc_sex,4)
st_matrix("freq_perc_sex", freq_perc_sex)
end

mat list freq_perc_sex
This will give me an output exactly as I want it in my table.

However, I would like to do this in a loop naming each matrix freq_perc_`var'. I can't get it to work though. Any inputs on the following code?:

Code:
foreach var of varlist (sex education treatment) {
estpost tab vac `var' , nototal matrix freq_`var'=e(b)' matrix perc_`var'=e(colpct)' matrix coljoinbyname freq_perc_`var' = freq_`var' perc_`var'
mata
freq_perc_`var'=st_matrix("freq_perc"_`var') freq_perc=colshape(freq_perc,4) st_matrix("freq_perc"_`var', freq_perc_`var')
 end

mat list freq_perc
}
I'm posting this in the Mata forum, as the latter code will work if I leave out the mata code but then I can't use the colshape.
How do I implement the ´var' in the st_matrix()? I guess this is where the problem is.

When running the code I get the following error
Code:
11. end
---Break---
r(1);
end of do-file
---Break---
r(1)
At the moment I'm unfortunately not able to produce a dataex example. I'm working on a secure server and it will take a while to re-write everything from the dataex output. If needed, I will gladly take the time to do so. Thank you very much for the help.