Can somebody please show me how to calculate stuff by groups, when I am calling a Mata function within my loop, instead of calling a Stata command?
For concreteness, lets say that I want to calculate the weighted mean of price by groups defined by rep. In Stata I would set up my loop like this:
Code:
sysuse auto, clear keep price weight rep egen groupsofrep = group(rep), missing gen wtmean = . summ groupsofrep, meanonly forvalues i = 1/`r(max)' { summ price [aw=weight] if groupsofrep==`i', meanonly replace wtmean = r(mean) if groupsofrep==`i' }
So how can I accomplish what I did above, but calling within my loop the Mata function -mean()- instead of the Stata command -summarize- ?
And the code calling the Mata function should be as fast as possible.
0 Response to How to construct loops doing something by group, with a Mata function inside the loop instead of a command?
Post a Comment