How do I create a stata local macro in python? [duplicate]

点点圈 提交于 2019-12-11 05:58:17

问题


Let me edit my question to clarify. Here is the python code:

decade_begin = 1970

while decade_begin <= 1994:
    for x in range(0, 10):
        a= decade_begin + x
    decade_begin = a+1
    decade_end=a

print "year_",decade_begin,"s" #start year 

The output of the last line is:

year_1980s
year_1990s

I want to be able to create a variable such that:

year_1990s = [a]

In stata this is quite easy, using a local macro `x'. But in python I think mixing string and int in a variable name is not allowed.

forval i = 1979/1994 {
whatever if year == `i' 
save year_`i'.dta, replace
}

Any ideas on how to implement in python?


回答1:


Something like this is a rough equivalent:

for x in ["apple", "banana", "orange"]:
    with open(x + ".data", "w") as outfile:
        outfile.write("whatever")



回答2:


If I understand correctly, you'd like to create a variable name using a string to name the variable. (The equivalent of local macros in Stata are called variables in Python). You can do this using the exec function:

>>> for i in range(1979, 1995):
...    exec("name_" + str(i) + " = " + str(i))

>>> print(name_1994)
1994

This code assumes you're using Python 3. If you're using Python 2, remove the outer parentheses for the lines with exec and print.

Using exec is not the best way to approach this problem in Python, however (as explained here). You will likely run into problems later on if you try to code in Python the same way you're used to coding in Stata.

A better approach might be to create a dictionary and use a different key for each number. For example:

>>> names = {}
>>> for i in range(1979, 1995):
...    names[i] = i
>>> print(names)
{1979: 1979, 1980: 1980, 1981: 1981, 1982: 1982, 1983: 1983, 1984: 1984, 1985: 1985, 1986: 1986, 1987: 1987, 1988: 1988, 1989: 1989, 1990: 1990, 1991: 1991, 1992: 1992, 1993: 1993, 1994: 1994}


来源:https://stackoverflow.com/questions/40729173/how-do-i-create-a-stata-local-macro-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!