1 of 26

Writing User-Written Stata Commands

Rosemarie Sandino

Technical Products Coordinator

RST, November 2021

2 of 26

Objectives

  • Describe the difference between a coding task and programming a command
  • Introduce the basic elements of a program
  • Write a user-written command using syntax

3 of 26

Coding Best Practices

  • What should we consider when we are writing code?
    • Coding as problem solving
    • Error control system

  • Three Overarching Elements of Coding
    • Functional
    • Reproducible
    • Documented

4 of 26

Coding vs. Programming

  • Coding task: do file with inputs, outputs, purpose(s), applies to a certain situation
    • Cleans data, creates variables, runs other do files, etc.
  • Program: completely generalized code with a purpose
    • Can apply to any data that fits the format it requires and create output
    • Solves a general problem, not a problem with specific dataset

5 of 26

Coding vs. Programming

  • Do file: Stata file that contains code
  • Ado file: Stata file that contains a program
    • Automatic do file
    • Stata stores ado files in your adopath
      • adopath command
      • Store your own commands in personal or plus

6 of 26

When to Write a User-Written Command

  • You are doing the same task three or more times
  • Multiple people/projects have to do the same task over time
  • Generalizable
    • Easier if your code for this follows the best practices!

7 of 26

Designing a User-Written Command

  • Map problem first into steps (inputs, outputs) and each step gets its own function
  • Your program should not do everything, it should have a single purpose and do it well
    • A subprogram can handle each specific task
  • Get a simple working version first before adding bells and whistles

8 of 26

Pseudocode

  • Turn high-level design into the format of code
  • Describe all of the functions the computer will need to do, but don’t code it out directly
  • Example for a t-test command:

// receive 2 variables from user

// confirm that variables 1 & 2 are numeric

// t-test variables

// display the p-value

9 of 26

Writing a User-Written Command

  • Stata has commands that structure the inputs you want to allow in a program
  • Two commands create the basic elements of a program
    • Program
    • Syntax

10 of 26

Program

  • Program defines a command for Stata
    • Program [define]
    • End
    • Program drop

  • Allows for multiple commands in the same file

11 of 26

Structure of A Command

  • How do we enter a command in Stata?
    • name of command
    • specifications
      • variables, type of variables, if, filename, replace, force, etc.
  • When we use the program command, we are telling Stata the name of the command
  • We need to tell Stata: 1) what else the program needs to run, 2) what it should expect, and 3) how we will reference it

12 of 26

Syntax

  • Stata already parses any code written after your command name
    • `0’: everything written after the command name
    • `1’, `2’, `3’, …, `n’: each space-separated word after the command name
  • syntax command parses code into specific macros
  • Specify how you want Stata to read the inputs

13 of 26

Syntax: Command

  • syntax defines how the program parses command inputs
  • varlist/varname: create `varlist’
  • if: creates `if’
  • in: creates `in’
  • using: creates `using’
  • =exp: creates `exp’
  • weight: creates `weight’

14 of 26

Pop Quiz!

15 of 26

Syntax: Options

  • Can create own name for each option
    • After a “,”
    • optionname: creates`optionname’
  • For options, capitalize what is the minimum Stata will recognize as an option
    • syntax DETail: creates `detail’ as long as “det” is typed
  • Two types of options
    • Takes a value
      • Ex. generate(varname)
    • A word
      • Ex. replace

16 of 26

Syntax: Defaults and Constraints

  • Varlist can have constraints
    • Ex: varlist(numeric max=2)
      • Only allows 1 or 2 variable in varlist
  • Options can have constraints too
    • Ex: syntax, input
      • Option input creates `input
      • `input’ = “” if Stata doesn’t find the word input
    • Ex: syntax, input(integer 1)
      • `input’ = 1 if Stata doesn’t find the word input

17 of 26

Syntax: Other Considerations

  • Anything can be optional by using brackets
    • [varlist] makes it optional to include variables
  • Macros will include “if”, “in”, “=“ unless you include a slash
    • syntax if : `if’ = “if foreign == 1”
    • syntax if/ : `if’ = “foreign == 1”

18 of 26

Syntax Practice

  • Write a command called “practice”
    • Extra credit: Allow up to 2 variables
  • Create an optional option “detail”
    • Extra credit: Make the option such that the user only has to type “d” to use the option
  • Your command should summarize the variables (use the summarize command) and use detail option if the user specifies
    • Hint: “summarize, “ is the same as “summarize”

19 of 26

Syntax Practice

20 of 26

Creating Your Own Errors & Checks

  • You have now:
    • Defined a command
    • Told Stata how to parse the inputs
  • Next step is to create your own errors and checks to ensure that the inputs to your program are the inputs that you want
    • dis as error “Your own error message”

exit [errorcode]

    • if `filename’ == “” local `filename’ = “output”

21 of 26

Try for yourself!

  • Create the “radsummit” command
  • Allow up to three numeric variables
  • Display:
    • Your name
    • The variables
    • Anything else you want!
  • Include optional option “red” that will show outputs in red (use help display)
    • Hint: as red

22 of 26

General Programming Best Practices

23 of 26

Best Practices

  • Include a comment that contains the version number, date modified, and author

  • Use sensible names for temporary variables and macros
  • Adopt Stata conventions when possible
  • Stata has ownership of commands that are in the English dictionary

24 of 26

Best Practices

  • Incorporate coding best practices
    • Tab lines consistently
    • Write within 80 columns
    • Organize code logically with code blocks and line breaks
    • Avoid # delim ;
  • Other people may want to troubleshoot or adjust your command
  • Every scenario should be covered by an error

25 of 26

Best Practices

  • Use quietly and capture
    • Every error should have a clear explanation
    • capture confirm will help show you the error so you can address it or show the user the error
  • Don’t change data in memory or add/drop variables unless the command explicitly states it will
    • Use temporary variables, sortpreserve, or preserve/restore
  • Always have user specify new names

26 of 26

References

  • Cox, Nick. 2005. “Suggestions on Stata Programming Style.” The Stata Journal 5, no. 4: 560-566. doi.org/10.1177/1536867X0500500406

  • StataCorp LP. NetCourse 251: Writing your Own Stata Commands.