简体   繁体   English

Stata - 如果变量名包含在本地,则运行代码

[英]Stata - run code if variable name contained in local

I would like to have an if condition in Stata which runs the code in braces for a certain variable only if that variable's name is contained in a local .我想在 Stata 中有一个if条件,只有当该变量的名称包含在local . Eg例如

if (`variable` element of `variablenames_local`) {
    gen variable2 = variable + 2
}

How can this be done in Stata?这在Stata中如何完成?

You can use extended macro functions for that, which are documented in help extended_fcn .您可以为此使用扩展宏函数,这些函数记录在help extended_fcn In this case help macrolist is very useful.在这种情况下, help macrolist非常有用。 (I never remember the names of those help-files, instead I usually type help macro or help local and follow the links in that help-file.) (我从不记得那些帮助文件的名称,相反,我通常键入help macrohelp local并遵循该帮助文件中的链接。)

sysuse auto, clear

local vars "price mpg foreign"

foreach var of varlist _all {
    if `: list var in vars' {
        di "do something smart with `var'"
    }
}

// alternatively:
foreach var of varlist `vars' {
    di "do something smart with `var'"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM