# st: -by- in ML

 From watt@fas.harvard.edu To statalist@hsphsun2.harvard.edu Subject st: -by- in ML Date Mon, 6 Jun 2005 17:31:27 -0400

```Hi,

I have a very simple question. I'm wondering how I can use -by- commands when
coding my own maximum likelihood estimation.

In particular, I have a panel and my likelihood function is only independent
across groups. The Stata manual gives a brief description of how this is done.
However, when following their commands exactly, I cannot get correct results.

As a simple practice before coding my own application, I have coded my own logit
command. To figure out how to use the -by- command, I would like to sum the log
likelihood within groups and then take the final log likelihood as a sum across
groups. This is not required for logit, but I would like to figure out how to
use the -by- command before doing my own application. I am using Stata 8.2.

Here is my code:

program mylogit2
version 8.0
args todo b lnf
tempvar theta1 a c group_sum last
mleval `theta1' = `b', eq(1)
quietly gen double `a' = exp(`theta1')/(1+exp(`theta1'))
quietly gen double `c' =  1/(1+exp(`theta1'))
by us_id: gen double `group_sum' = sum(ln(`a'^(\$ML_y1) * `c'^(1-\$ML_y1)))
by us_id: gen double `last' = (_n==_N)
mlsum `lnf' = `group_sum' if `last'
end

ml model d0 mylogit2 (y = x1 x2)
ml check
ml search
ml maximize

This does not seem to work.

The following does, so, perhaps, the -by- function is to blame.

program mylogit2
version 8.0
args todo b lnf
tempvar theta1 a c
mleval `theta1' = `b', eq(1)
quietly gen double `a' = exp(`theta1')/(1+exp(`theta1'))
quietly gen double `c' =  1/(1+exp(`theta1'))
mlsum `lnf' = ln(`a'^(\$ML_y1) * `c'^(1-\$ML_y1))

end

ml model d0 mylogit2 (y = x1 x2)
ml check
ml search
ml maximize

Much thanks.

Stanley

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```