仅当 Stata 中不存在该列时如何生成该列?

How to generate column only if that column doesn't exist in Stata?

我可以使用

创建变量logincome
generate logincome = log(income)

但是从第二次执行 do file 开始,它显示了一个错误:

variable logincome already defined

如果变量已经存在,如果 Stata 询问我是否要跳过或覆盖它,那就太好了。

我试图找到 Stata 的一些 if 语句来执行此操作...比如如果 logincome 存在则跳过以下行。但是我的谷歌搜索没有找到类似的东西。

这类问题有很多可能的解决方案。请参阅 help confirmhelp asserthelp ifcmd 等开始。但是,一个简单的解决方案是

capture generate logincome = log(income)
如果紧随其后的命令产生错误,

capture 将防止您的代码中断。另请注意,help capture 将有助于在其他(更实质性的)情况下使用 confirmassertif 命令。

然而,更进一步,您可能希望以 clearuse 语句开始您的 do 文件,以便在每次执行您阅读的 do 文件时在未更改的数据中,然后执行您编写的命令。