Monday, May 14, 2012

An easy way to conduct f-tests on regression coefficients

Suppose you want to conduct a joint test for significance on coefficients of variables that have been expanded in a regression using the xi command. For example suppose you ran the command:

xi: svy, subpop(rual) : y i.lfs i.roofmat  var5 var6 var7 var8

doing an f-test manually on the each of the expanded variables would involve typing (or copying and pasting) the expanded variables, something like:

test _Ilfs_2 _Ilfs_3 _Ilfs_5 _Ilfs_6 _Ilfs_10
test _Iroofmat_2 _Iroofmat_5 _Iroofmat_6 _Iroofmat_7 _Iroofmat_8

As you can see, the numbers on the xi expanded variables do not necessarily increase by one. And this can be cumbersome to type out, or copy and paste, especially if you have many such categorical variables. I'm sure someone has solved this already, but I couldn't find a solution through a web search, so I made my own.

The following program, which you would run after running the reg command, will automatically run f-tests on each group of xi expanded categorical variables. So you would use this program as follows:

xi: svy, subpop(rual) : y i.lfs i.roofmat  var5 var6 var7 var8
easyftest

To use this, just copy the program below and save it as an .ado file in your Stata path to your personal programs directory. The filename should be "easyftest.ado". Let me know if you have any trouble with it. Good luck!

program define easyftest

    local xivars "`_dta[__xi__Vars__To__Drop__]:'"
    local word1 : word 1 of `xivars'
    local pattern = regexr("`word1'","_[0-9]+$","_")
    // di "word1 = `word1'"
    // di "pattern = `pattern'"
    local ftestvars1 "`word1'"
    local count = 0
    local ftestcount 1
    foreach var of local xivars {
        local count = `count' + 1
        if (`count' != 1) {
            local w : word `count' of `xivars'
            // di "w: `w'"
            // check to see whether the next variable is to be included in this list of f-test variables
            if (regexm("`w'","^`pattern'[0-9]+$")) { // there is a match - add this to this list of ftest variables
                // di "pattern match!"
                local ftestvars`ftestcount' "`ftestvars`ftestcount'' `w'"
                // di "ftestvars`ftestcount' : `ftestvars`ftestcount''"
            }   
            else { // no match, create a new list of f-test variables, add this variable to it as the first element, and replace the pattern
                local ftestcount = `ftestcount' + 1
                local ftestvars`ftestcount' "`w'"
                local pattern = regexr("`w'","_[0-9]+$","_")
            }
        }
    }
   
    forv k = 1/`ftestcount' { // Do all the ftest
        // di "ftestvars`k' : `ftestvars`k''"
        // return local ftestvars`k' `ftestvars`k''
        test `ftestvars`k''
    }
    // return scalar N = `ftestcount'

end

No comments: