Good evening,

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'
}
Now supposed that the Stata command -summarize- does not exist, but a very kind person has written the Mata function -mean()-.

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.