I am writing a Stata do
file and I would like to provide default values if the user does not supply some parameters. To do so, I woud like to check if a macro is undefined.
I have come up with a hacky way to do this:
*** For a local macro with the name value:
if `value'1 != 1 {
...do stuff
}
But I would like to know if there is a idiomatic way to do this.
The command local tells Stata to keep everything in the command line in memory only until the program or do-file ends. If you plan on analyzing only one data set then the global command shouldn't cause you any problems.
In this diagram, varlist denotes a list of variable names, command denotes a Stata command, exp denotes an algebraic expression, range denotes an observation range, weight denotes a weighting expression, and options denotes a list of options.
In Stata, a global macro is something that is stored in memory and can be used anytime during a Stata session by reference to its name (a local macro differs basically inasmuch it can be used only within a circumscribed piece of a program or a do-file).
Notice that instead of using the actual value of the mean of read in this command, we used the name of the returned result (i.e. r(mean)), Stata knows when it sees r(mean) that we actually mean the value stored in that system variable.
If it's undefined, the contents of the macro would be empty. You can do this:
if missing(`"`mymacroname'"') {
display "Macro is undefined"
}
The quotes aren't really needed if the macro will contain a number. The missing(x)
function can handle strings and numbers. It is kind of like testing (x=="" | x==.)
Placing `'
around "`mymacroname'"
allows the macro to contain quotes, as in local mymacroname `"foo"' `"bar"'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With