Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: implementing an equivalent of egen mean() in Mata.


From   Christophe Kolodziejczyk <ck.statalist@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   st: implementing an equivalent of egen mean() in Mata.
Date   Thu, 1 Sep 2011 14:37:15 +0200

Dear Stata list members

I want to implement a mata function wich computes group averages over
the columns of a matrix. In other words I want to implement in Mata an
equivalent of egen with mean().
I have not been able to find such a function in the mata manual.

I have written the following function by using panelsetup(). But
because of the loop over the observations it tends to be slow with
large samples. Any idea how to make it work faster? Any other
suggestions to the code is also welcome.
Thanks for your help
Christophe

real matrix meani(real vector id, real matrix x)
{

    real vector info, xi, meanix
    real scalar ninfo, i

    info=panelsetup(id,1)
    ninfo=rows(info)

    meanix=J(rows(id),cols(x),.)

    for (i=1;i<=ninfo;i++) {
        xi = panelsubmatrix(x, i, info)
        meanix[info[i,1]::info[i,2],.]=J(rows(xi),1,mean(xi))
        }

    return(meanix)
}
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index