我正在尝试使用Python进行统计分析.
在Stata中,我可以定义本地宏并根据需要展开它们:
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
Run Code Online (Sandbox Code Playgroud)
所以代替:
reg2 mpg, indepvars("weight foreign price") results("y")
Run Code Online (Sandbox Code Playgroud)
我可以:
local options , indepvars(weight foreign price) results(y)
reg2 mpg `options'
Run Code Online (Sandbox Code Playgroud)
甚至:
local vars weight foreign price
local options , indepvars(`vars') results(y)
reg2 mpg `options'
Run Code Online (Sandbox Code Playgroud)
Stata中的宏帮助我编写干净的脚本,而无需重复代码.
在Python中我尝试了字符串插值,但这在函数中不起作用.
例如:
def reg2(depvar, indepvars, results):
print(depvar)
print(indepvars)
print(results)
Run Code Online (Sandbox Code Playgroud)
以下运行正常:
reg2('mpg', 'weight foreign price', …Run Code Online (Sandbox Code Playgroud)