user10162045
user10162045

Reputation:

Equivalent of Stata macros in Python

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)

I found a similar question but it doesn't answer my question:

There is also another question about this for R:

However, I could not find anything for Python specifically.

I was wondering if there is anything in Python that is similar to Stata's macros?

Upvotes: 2

Views: 4218

Answers (1)

g.d.d.c
g.d.d.c

Reputation: 47988

It looks like you just want the * and ** operators for calling functions:

regargs = 'mpg', 'weight foreign price', 'y'
reg2(*regargs)

Use * to expand a list or tuple into positional arguments, or use ** to expand a dictionary into keyword arguments to a function that requires them.

For your keyword example, you need to change the declaration a little bit:

regargs = dict(depvar='mpg', covariates='weight foreign price', results='y')
reg2(**regargs)

Upvotes: 1

Related Questions