program def regresby
* regression residuals by byvarlist
*! NJC 1.0.0 5 May 1998
    version 5.0
    local varlist "req ex"
    local if "opt"
    local in "opt"
    local weight "aweight fweight"
    local options "BY(string) Generate(string) *"
    parse "`*'"

    if "`generat'" == "" {
        di in r "generate( ) option required"
        exit 198
    }
    else confirm new variable `generat'

    unabbrev `by'
    local by "$S_1"

    tempvar res thisres group touse

    mark `touse' `if' `in'
    markout `touse' `varlist'

    qui gen `res' = .

    sort `touse' `by'
    qui by `touse' `by' : gen `group' = _n == 1 if `touse'
    qui replace `group' = sum(`group')
    local ngroup = `group'[_N]

    local i 1
    while `i' <= `ngroup' {
        qui regress `varlist' if `group' == `i' [`weight' `exp'], `options'
        predict `thisres', residual
        qui replace `res' = `thisres' if `group' == `i'
        local i = `i' + 1
        drop `thisres'
    }

    gen `generat' = `res'
end