问题描述
我正在尝试使用Python进行统计分析.
I am trying to use Python for statistical analysis.
在Stata中,我可以定义本地宏并根据需要展开它们:
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
所以代替:
reg2 mpg, indepvars("weight foreign price") results("y")
我可以做到:
local options , indepvars(weight foreign price) results(y)
reg2 mpg `options'
甚至:
local vars weight foreign price
local options , indepvars(`vars') results(y)
reg2 mpg `options'
Stata中的宏可以帮助我编写简洁的脚本,而无需重复代码.
Macros in Stata help me write clean scripts, without repeating code.
在Python中,我尝试了字符串插值,但这在函数中不起作用.
In Python I tried string interpolation but this does not work in functions.
例如:
def reg2(depvar, indepvars, results):
print(depvar)
print(indepvars)
print(results)
以下运行正常:
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:
对于R还有另一个问题:
There is also another question about this for R:
但是,我找不到专门针对Python的任何东西.
However, I could not find anything for Python specifically.
我想知道Python中是否有类似于Stata宏的内容?
I was wondering if there is anything in Python that is similar to Stata's macros?
推荐答案
您似乎只希望*
和**
运算符用于调用函数:
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)
这篇关于等价于Python中的Stata宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!