简体   繁体   中英

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 . Eg

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

How can this be done in Stata?

You can use extended macro functions for that, which are documented in help extended_fcn . In this case help macrolist is very useful. (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.)

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'"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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