If subroutines

April 10, 2009 at 2:36 pm 1 comment

| Gabriel |

For a very long time I’d been aware that you could add “if” as a suffix to some commands, for instance:

drop if baddata==1

This is one of the first bits Stata syntax you learn but I’m embarrassed to say that I only recently learned that there’s also an “if” subroutine that works like this:

if "`pope'"=="catholic" {
 disp "duh! what do you expect him to be, a wiccan?"
else {
 disp "are you sure? because i'm pretty sure he's catholic"

Why would you want to do this? A somewhat trivial reason is that it’s an easy way to flag things for code-folding if you’re using an editor that supports that kind of thing.

The real reason is for programming. “If” subroutines are very useful if you want to try different versions of something and you don’t want to completely rewrite the script. What you do is put the optional parts inside of an “if” subroutine and then change the condition to be true when you want to exercise the option. This is similar to just commenting the line out but has the advantage that it’s much easier to apply to multiple lines of code.

The real trick though is if you can define the truth condition at the beginning, then let multiple “if” clauses propagate the contingency throughout the code. There are two ways to do this. One is to use a global at the start of a do-file. For instance, imagine that you had been using a lot of variables as linear but wanted to experiment with logging some of them. You could write a do-file that looks like this and all you’d have to do is change the first line to switch from the log vs linear version of the do-file:

global logarithms   "yes"
use data, clear
if "$logarithms"=="yes" {
  disp "note, this is the log version"
  replace x1=ln(x1)
  replace x2=ln(x2)
  replace x3=ln(x3)
reg y x1 x2 x3 x4 x5 
if "$logarithms"=="yes" {
 esttab using results_log.txt, replace
else {
 esttab using results_linear.txt, replace

Likewise, if you’re using the “program” syntax it can be extremely useful to write options into the program syntax such that if the option is invoked the program runs a little differently. This works exactly the same as the global above except that it would be a local defined by the program’s arguments. Another programming application is to avoid syntax errors. For instance, you can use “if” with esttab so that if “filename.txt” exists then you append results to it, but if it doesn’t then you just save to that location.

Entry filed under: Uncategorized. Tags: .

It’s like we finish each others sentences! (is that a good thing?) The greatest diffusion story ever told

1 Comment

  • 1. Globals « Code and Culture  |  April 25, 2009 at 11:42 am

    […] options or switches. As described in a previous post, one of the things you can do with this is use the “if” syntax to turn entire blocks of code on or off. There are other ways to use the switches. For instance, […]

The Culture Geeks

%d bloggers like this: