Dependencies: making sure your ado/do-files run in any computer

Imagine that you write a do-file or an ado-file in which you use one or serveral user-written commands available in SSC (or any other repository). However, when you share it with someone else, that person is constantly frustrated because your code is constantly requesting the use of a command that has not been installed in their computers. You could solve your problem by always adding the following code at the beginning of do/ado-file.

if ("${pfx_cmds_ssc}" == "") {
  * list of commands avialble in SSC 
  local cmds apoverty ainequal fastgini quantiles prosperity hoi /* 
  */   iop drdecomp skdecomp adecomp
  
  * Check whether the command is installed.
  foreach cmd of local cmds {
    capture which `cmd'
    if (_rc != 0) ssc install `cmd' // isntall if not in local computer
  }
  
  adoupdate `cmds', ssconly   // check if commands are up to date
  if ("`r(pkglist)'" != "") adoupdate `r(pkglist)', update ssconly // those that are not. 
  global pfx_cmds_ssc = 1  // make sure it does not execute again per session
}

Explnation of the code

  1. Enclose the whole procedure inside the condition if ("${pfx_cmds_ssc}" == "") to make sure it only cheks for updates once per session. Once the updates are done, you close the condition with global pfx_cmds_ssc = 1. The pfx in the name of the global macro refers to a prefix that you may change in order to make the global unique.

  2. Define a local macro (local cmds) with all the commands that you use in your code.

  3. Run a loop over each command to check whether the command is avaialable in the local computer. You check if the command is available using the command which.

  4. Finally, you check if all your commands are up to date (adoupdate `cmds', ssconly) and update those that are not. This final step is optional in case you’re using a particular version of a command that works better or have a different syntax than a newer version. In Stata, this kind of problems does not happen as often as it does in R or, even more often, in Python.

Economist/Data Scientist

My research interests include … matter.