Friday, June 29, 2012

A note on debugging in Stata


* As far as I know, there is no guide to debugging in Stata.  This post touches on a few topics though as with any programming language you really just need to spend many hours of trial and error to figure out what works and what doesn't and what it looks like when things are not working.

* As an interpretive language (one that takes commands one by one) Stata can be often times very easy to debug in.

* For instance:

sysuse auto

* Imagine you want to do a IVreg

ivregress  trunk foreign make

* This command for instance produces an error and the best thing to do at that point is to query the documentation for the proper syntax of Stata.

help ivregress

*  ivregress estimator depvar [varlist1] (varlist2 = varlist_iv) [if] [in] [weight] [, options]

* The way you read this is the first entry is the name of the command

* After the command the different elements are deplained in the pages of the command.  Anything that is in [] is optional while anything not is required.

* The best way for me to find out how to write a Stata command is to look at an example usually listed on the bottom of a command then modify it to fit my purposes.

* However, beyond this one line command debugging things can get much trickier.

* Imagine:

forv i=1/10 {

forv v=1/10 {

gen var_`i'_`v' = `i'*`v'

gen var_`i'_`v'2 =  var_`i'_v^2

}
}
}

* This code will not work.  It might be easy to identify what is going wrong with it for an experienced programmer.

* However, often macros make mistakes very difficult to identify because what is actually hapenning in the commands is difficult to observe.

* One way to help in this is to add lots of display commands so that you can see what commands are actually being sent to Stata.
clear

forv i=1/10 {

di "i = `i'"

forv v=1/10 {

di "v = `v'"

di "gen var_`i'_`v' = `i'*`v'"
gen var_`i'_`v' = `i'*`v'

di "gen var_`i'_`v'2 =  var_`i'_v^2"
gen var_`i'_`v'2 =  var_`i'_v^2

}
}
}

* We can see that {gen var_`i'_`v'2 =  var_`i'_v^2} is the source of the problem because var_`i'_v^2 should be var_`i'_`v'^2

* Correcting that we still have one more error.


clear

forv i=1/10 {

di "i = `i'"

forv v=1/10 {

di "v = `v'"

di "gen var_`i'_`v' = `i'*`v'"
gen var_`i'_`v' = `i'*`v'

di "gen var_`i'_`v'2 =  var_`i'_`v'^2"
gen var_`i'_`v'2 =  var_`i'_`v'^2

}
}
}

* That is an extra bracket, this is a very typical error
* Likewise, having a unpaired { will cause stata to give an unexpected end of file error.

2 comments:

  1. -set trace on- is useful for debugging. I also found helpful William Gould's presentation here: .

    ReplyDelete
  2. Let's try that link again: stata.com/meeting/uk10/UKSUG10.Gould.pdf

    ReplyDelete