How to write programs (also called commands or functions) in Stata
This is an introduction to how to write programs in Stata. To try this out yourself, download this Gist by clicking Download Zip. Unpack the .zip file and edit the path global in the
runfile.do. Then follow these instructions and run the corresponding section of the run file.
If you have any questions or want us to add another examples on how you can expand
myhist.ado as us in the comment section below.
It is common in computer science that the first function/command you write is a simple command that just display the message Hello World!. That is what the program in
Here we are set-by-step writing a command that takes a variable and creates a histogram with that variable. In a real life scenario this command could be expanded so that the command includes a lot of
histogram options so that you can easily apply them to many histograms by typing
myhist varC etc.
This is the simplest possible version of this command. The syntax takes exactly one variable (because we use
varname instead of
varlist) and create a histogram of the distribution in that variable.
In this version we have added one option called
title() that takes a string. We add "DIME -" in front of that string and then use it as the title of the historgram.
What you call your options does not matter at all to Stata. myhist_v3.ado gives the exact same result as myhist_v2.ado, but the
title() option is called
xyz(). You should always chose a name that make sense to humans as it will make it easier for humans to read the code - so xyz is a terrible name - but it makes no difference to Stata.