SAS macro to run Stata code from within SAS

The STATA_WRAPPER SAS macro is installed when you download usesas.


But you can also download it here:


If you are not prompted to "Save To Disk", then right-click the link and choose "Save Link Target As..."  Otherwise, you will need to save the web page to your computer.  Make sure you save the

file as a plain text file not an htm/html file.


The best way to download STATA_WRAPPER is to use Stata's command

ssc install to install usesas which STATA_WRAPPER requires to be installed anyway.  The file will be saved in whatever directory Stata saves downloaded files that begin with the letter "s".  The Stata command findfile will help you find the file



macro is a text file that can be edited in any word processing software.  After you edit the file, save it as a text file.


Disclaimer:  There is no warranty on this software either expressed or implied.  This program is released under the terms and conditions of GNU General Public License.



Programmer:  Dan Blanchette
The Carolina Population Center
The University of North Carolina
Chapel Hill, NC  USA
Date:  20Mar2008
Last updated:  28Mar2011

Input:  Most recently created SAS WORK dataset and some Stata code.

Output:  by default it will be included in the SAS output window/.lst file.

Dependency:  You need to have Stata installed on your computer and have the Stata command usesas installed for STATA_WRAPPER to load your most recently created SAS WORK dataset into Stata.  It would also be a good idea to have the Stata command savasas installed as well if you want to pass data back to your SAS session.



STATA_WRAPPER could be thought of as "SAS-Callable Stata" since it runs the Stata software that is installed on the same computer that you are running SAS on.  By default the STATA_WRAPPER SAS macro loads the most recently created SAS dataset that is located in the WORK library/directory into Stata and runs the Stata code written after the line:
%stata_wrapper(code) datalines; 
The log of the Stata code will be included in the SAS output window/.lst file unless an output directory name is specified.  STATA_WRAPPER can also submit Stata code stored in any Stata do-file stored anywhere on your computer as well.  The most recently created SAS dataset will be available to use in Stata as well unless the "-nodata" option is specified.  Non-Windows users need to think of their Stata code being run in batch mode.  So consider that windows that display graphs will not be saved unless you use the graph save command.  When saving files, you need to specify the directory you want to save to as the current directory is the temporary SAS WORK library/directory which gets deleted when the SAS session is closed.

NOTE:  If you are using SAS on Windows, an interactive Stata session will be started by STATA_WRAPPER.  Do not close the Stata window until the do-file submitted to Stata by STATA_WRAPPER has finished running.  STATA_WRAPPER when run in SAS on Linux/UNIX will run Stata in the background.


Required input to STATA_WRAPPER:

Unless the option -nodata is specified, STATA_WRAPPER needs to have the most recently created dataset by SAS to be in the WORK library/directory and some Stata code to process.  STATA_WRAPPER expects Stata code to be submitted to STATA_WRAPPER using the call to STATA_WRAPPER:
 %stata_wrapper(code) datalines; 
See the examples below on how to submit Stata code to STATA_WRAPPER.



NOTE:  Options can be used in any order.  You can specify as many as you want or none at all.
Used when only writing Stata code to be submitted by STATA_WRAPPER.  No other options can be used when using the code option.  You have to have datalines; after the call to STATA_WAPPER:
 ** This invocation of stata_wrapper does not submit the code to Stata.  *;
   *  That happens later. **;

  %stata_wrapper(code) datalines;
   /** this is code that will be run by Stata **/
   svyset myPSUvar [pweight= myWeightVar], strata(MyStratumVar)
   svy:mean income weight height, over(agegroup race)
  ;;;;  ** You should put at least one semi-colon after all your Stata code **;

  ** Your Stata code cannot contain any semi-colons.  Do not use #delimit; **;

  ** If you really want to use semi-colons in your Stata code, use "datalines4;" **;
   *  and end your Stata code with 4 semi-colons starting at the very  **;
   *  beginning of the line (column 1 through column 4) **;

  %stata_wrapper(code) datalines4;
    /** this is code that will be run by Stata **/
    svyset myPSUvar [pweight= myWeightVar], strata(MyStratumVar);
    svy:mean income weight height, over(agegroup race);
  ;;;;  ** You need 4 semi-colons starting at the beginning of the line. **;

Indicates not to load the most recently created SAS dataset in the WORK library/directory into Stata.  This should be used when your Stata code does not require that dataset.

Specifies NOT to create value labels (which is the default) from SAS user-defined formats that are stored in a SAS formats catalog file that has the same name as the dataset and is in the WORK library/directory.  For example:  MySasData.sas7bcat .  If this file doesn't exist, usesas will look for the file formats.sas7bcat in the WORK library/directory.

(Windows only option, not for Linux/UNIX) Keep interactive Stata running.  You have to exit/close Stata before you can return to SAS or exit/close SAS since SAS is waiting for Stata to stop running.

Includes the Stata log in your SAS log rather than your SAS output window/.lst file.

If an output directory is specified and the output files you want to output already exist, -replace will then overwrite them with the files generated by STATA_WRAPPER.

Since STATA_WRAPPER uses the Stata command usesas to load the most recently created SAS dataset in the WORK library/directory the following are options to be used by usesas when called by STATA_WRAPPER:

Specifies to encode long SAS character variables like the Stata command encode.  Character variables that are too long for a Stata string variable are maintained in value labels.

Specifies that numeric variables that would otherwise be stored as numeric type double be stored with numeric type float.  This option should only be used if you are certain you have no integer variables that have more than 7 digits (like an ID variable).

Specifies that double quotes that exist in string variables are to be replaced with single quotes.

Debugging options
Puts the files generated by STATA_WRAPPER used to create the Stata log file in the current directory or the directory named in the pathname provided in the call to the STATA_WRAPPER macro if one was provided.


How to use the STATA_WRAPPER macro:

Using the STATA_WRAPPER macro requires that you understand how to use the %include SAS statement and that you know how to call a SAS macro.

For example, if you have copied this file to "C:\SASmacros\", then you tell SAS about this macro by adding the following line to your SAS program:
  %include "C:\SASmacros\"; 
But STATA_WRAPPER is likely to be installed in the directory where Stata installs files that begin with the letter "s":
  %include "C:\ado\plus\s\"; 
The include statement makes SAS aware of the STATA_WRAPPER macro which is in the file  To use the macro you have to make a call to it.  To do that you add a line like the following to your SAS program:
 %stata_wrapper([options], "[folder to save Stata output]" ); 
But you don't really have to specify anything if you want to use the defaults:

    ** create a dataset that contains only the observations and 
     *  variable(s) needed for the Stata command to be run:  **;
    data test;
     set my_data (keep= age income
                  where= (gender = 1));
    ** Write some Stata code that will be submitted to 
     *  Stata by STATA_WRAPPER **;
    %stata_wrapper(code) datalines;
      [stata code]
      [more stata code]
    ** run the STATA_WRAPPER macro: **;
Or you can submit a Stata do-file saved in some other directory:
     %stata_wrapper(code) datalines;
      do "C:\my_project\"
      [more stata code if you want]

    ** run the STATA_WRAPPER macro: **;
The information inside the parentheses is passed on to the STATA_WRAPPER macro.  The first string of information is any/all STATA_WRAPPER options.  The second string of information is the location you want to save your Stata results/log file if you do not want it printed in the SAS output window/.lst file.  This is somewhat like a libname statement.



    ** Include macro once in a SAS session and call it **;
     *  as many times as you like in that session.     **;
    %include "C:\ado\plus\s\"; 

    ** This makes a copy of the SAS dataset in the in the work library. **;
    data work.ToBeStata;   
     set in.mySASfile (keep= math cses one school gender
                       where= (gender = 1));
    ** write some Stata code to be submitted by STATA_WRAPPER: **;
    %stata_wrapper(code) datalines;
     eq cses: cses
     eq one: one
     gllamm math cses, i(school) eqs(one cses)  diff adapt nrf(2)
    ;;;; ** end Stata code with at least on semi-colon **;
    ** Have STATA_WRAPPER submit the above Stata code to Stata  **;


   ** Just have STATA_WRAPPER submit some Stata code you have already written **;
    *  that will use the most recently created SAS dataset **;
   data work.ToBeStata;
    set in.mySASfile (keep= state gender race region
                      where= (region= "SE"));

   %stata_wrapper(code) datalines;
    do "C:\MyData\"

   ** Have STATA_WRAPPER submit the above Stata code to Stata  **;

    ** Save the Stata log file "_[some_big_number]_stata_code.log"  **;
    ** in "C:\MyData\", overwriting it if it already exists.    **;

    ** Run the Stata do-file "" in "C:\MyProject\" and **;
     * save the Stata log file "_[some_big_number]_stata_code.log"  **;
     * in "C:\MyData\", overwriting the log file if it already exists.    **;

   %stata_wrapper(code) datalines;
    do "C:\MyProject\"


This example is like a USESTATA SAS macro

    %stata_wrapper(code) datalines; 
      use "C:\My Project\Data\some_data.dta"
      savasas using "some_data.sas7bdat"

    ** specify not to use the most recently created SAS dataset in WORK **;
     * since your Stata code does not need it. **;

    ** now you can access this dataset from your WORK library/directory **;
     *  because no directory name was specified in the call to savasas above. **;
    proc contents data= work.some_data;

The above example assumes that Stata is not set up to cd to some other directory when Stata is started up.  If you are not in the SAS WORK library/directory at the moment when savasas is invoked you can use the Stata command sas_work to cd you to that directory.  This command is only available in Stata while running STATA_WRAPPER.  Here is an example using sas_work:

    %stata_wrapper(code) datalines;
      use "C:\My Project\Data\some_data.dta"
      return list  // this is optional but shows that 
                   //  the local macro r(sas_work) exists now
      savasas using "some_data.sas7bdat"
    proc contents data= work.some_data;

usesas usually sets your memory large enough, but this is an example of what to do if you need more because you are using a version of Stata previous to Stata 12:

    %stata_wrapper(code) datalines;
     preserve   /** temporarily store data **/
     clear      /** clear data so that you can set memory **/
     set mem 1g /** set memory to 1 gigabyte **/
     restore    /** load previously stored data **/
     gllamm y do_want other_self blame express, i(person) ///
                      link(logit) family(binom) adapt nip(5) 




These are instructions to edit the file.

NOTE:  If you are setting up this macro on your computer for the first time, you can choose which version of Stata you are going to have STATA_WRAPPER use.  If you do not choose to set one of the following switches, STATA_WRAPPER will figure out what version of Stata you are running for you.  This may add a noticeable amount of time to processing so you may want to set these switches to the correct version of Stata.  You can easily figure out what version of Stata you are using by looking at the top of your results window in Stata or by typing in the Stata command about at the Stata command line.  One advantage of leaving STATA_WRAPPER to figure out what version of Stata is being used is that when you upgrade your version of Stata you will not have to update STATA_WRAPPER.

NOTE:  If you are running STATA_WRAPPER on the UNIX/Linux platforms then you need to be able to start a Stata batch job by:
 stata -b do 
If not, then change the setting of the ustata macro variable.
%let ustata=stata; 
  /* This may work:
  %let ustata=/usr/local/stata/stata-se;  */ 

If you are running STATA_WRAPPER on the Windows platform, you need to tell STATA_WRAPPER where the stata.exe file is located.  If you do not know where your stata.exe is located, find your Stata short-cut icon, right click on it, choose "properties", and look in the "target" field.  This will show you where the stata.exe is located on your hard drive.

Change what is inside the parentheses to the location of your stata.exe file.
%let wstata=%nrstr(C:\Stata\stata.exe);  ** This may work. **;
In earlier versions of Stata, the Windows Stata executable file is named wstata.exe.

Wink Plone Theme by Quintagroup © 2013.

Personal tools
This is themeComment for Wink theme