Hello,

My goal is to collect counts and percentage of each level of a categorical variable in a PostFile, looping several categorical variables each with a variable number of categories/levels
I have come up with the following code:

#delimit ;

local CategVar
"
sex vit_intermacs vit_nyha hx_crt hx_icd mr_degree tr_degree vad_acei vad_aldant vad_arb vad_bb vad_ecmo vad_furo vad_statin vad_strategy death

";

postfile stats str32 varname obs freq perc using TBL_RiVmiRNA_CATEG2, replace;

* LOOP FOR CATEGORICAL VARIABLES ;
foreach var of varlist `CategVar' {;
capture noisily preserve; // capture here is mandatory, the script stops otherwise, BUT we need the preserve
quietly tabulate `var', gen(`var');
drop if missing(`var');
capture noisily contract `var', percent(percentage);
egen N = total(`var');
post stats ("`var'") (N) (_freq) (percentage);
restore;
};

postutil clear;
* terminato il loop, eliminiamo dalla memoria del comando Post le statistiche or ora calcolate;

#delimit cr

That is, I guess, working fine, EXCEPT for the fact that stores in just one line only stats about the last level of the variable, there is a way to modify it so to store on several rows stats for each level of each variable ?

Thank you in advance,

Diego