|
Many Stata users refer to do-files as programs. This colloquialism is accurate, but the term "program" also has a particular meaning within Stata. Specifically, a program represents a Stata subroutine that "allows [users] to define a chunk of code in one place and run it repeatedly" ("Programming in Stata," 2007). Thus, it is a powerful tool for automating one's work in Stata. A segment of code that is a program begins with the command program define and concludes with the command end. I've named the short program below "example."
|
Now that I've defined the program, I can begin passing arguments to it. I do this by entering the program's name as a command (i.e., example) followed by the information I want the program to substitute in place of the local macro `1'. Programs parse arguments based on spacing unless otherwise instructed. In the first line of code shown below, the command example program tells Stata to drop the word "program" into the slot denoted by `1', thereby yielding the second line of output. Because Stata reads arguments based on spacing, the fourth line of code does not display the phrase "program that works." I can remedy this by enclosing the phrase in quotation marks, as demonstrated in the fifth and sixth lines of code below.
Importantly, the local macro`0' instructs Stata to select everything following a given program's command (e.g., example), while `1' instructs Stata to select the first space-delimited element or value, `2' instructs Stata to select the second space-delimited element or value, and so on. Users can rename local macros using the command args followed by the preferred names. Stata continues to parse the renamed arguments based on their position (i.e., the first renamed argument equals `1', the second renamed argument equals `2', etc.). In the example below, I renamed the local macro `1' as `one'. Renamed arguments must still be enclosed in directional quotation marks.
|
Notably, programs will break if they've already been defined in Stata.
To avoid this error message, use the command program drop followed by the name of the program.
You can also begin your program using the capture command to prevent it from breaking when the program has previously been defined. The capture command should be used with care. Indeed, capture tells Stata to continue running a do-file without breaking even in the presence of an error. However, capture is quite useful in the case of programs. When used prior to defining a program, it instructs Stata "to get rid of a program ... if it exists, and do nothing if it doesn't" ("Programming in Stata," 2007).
For more information about programs, refer to section 18.4 of Stata's user manual.
|