Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

I am trying to use Python for statistical analysis.

In Stata I can define local macros and expand them as necessary:

program define reg2

    syntax varlist(min=1 max=1), indepvars(string) results(string)

    if "`results'" == "y" {

        reg `varlist' `indepvars'

    }

    if "`results'" == "n" {

        qui reg `varlist' `indepvars'

    }

end

sysuse auto, clear

So instead of:

reg2 mpg, indepvars("weight foreign price") results("y")

I could do:

local options , indepvars(weight foreign price) results(y) 

reg2 mpg `options'

Or even:

local vars weight foreign price

local options , indepvars(`vars') results(y) 

reg2 mpg `options'

Macros in Stata help me write clean scripts, without repeating code.

In Python I tried string interpolation but this does not work in functions.

For example:

def reg2(depvar, indepvars, results):

    print(depvar)

    print(indepvars)

    print(results)

The following runs fine:

reg2('mpg', 'weight foreign price', 'y')

However, both of these fail:

regargs = 'mpg', 'weight foreign price', 'y'

reg2(regargs)

regargs = 'depvar=mpg, covariates=weight foreign price, results=y'

reg2(regargs)

1 Answer

0 votes
by (108k points)
To resolve your query, Pyexpander provides some of this kind of functionality in Python but it is not really a replacement. For different use cases, you will need a different approach to mimic macro expansion. In contradiction with Stata, there is no uniform way of doing this everywhere.

My recommendation is to familiarize yourself with Python's conventions rather than trying to program things the "Stata way". For instance, it is helpful to memorize that local and global macros in Stata correspond to variables in Python (local in a function, global outside), while variables in Stata correspond to Pandas.Series or a column of a Pandas.DataFrame. Likewise, Stata ado programs correspond to functions in Python.

Browse Categories

...