Warm tip: This article is reproduced from stackoverflow.com, please click
stata wildcard

Set of wildcard matches from variable names

发布于 2020-04-08 15:41:23

I have a set of variables, say varA, varB, and varC.

How can I loop over only the postfixes A, B, and C?

I know I can get all of the matching variables as follows:

des var*

              storage   display    value
variable name   type    format     label      variable label
-------------------------------------------------------------------------------------------------------------------------------------
varA            float   %9.0g                 
varB            float   %9.0g                 
varC            float   %9.0g                 

However, is there a way to extract only the matching component and loop over it?

The ideal code would be something like the one below:

des var*

foreach postfix in `r(wildcardmatches)' {
    display "`postfix'"
}

If the set r(wildcardmatches) existed.

Questioner
ASV
Viewed
39
Nick Cox 2020-02-01 01:21
* sandbox 
clear
set obs 1 
foreach v in varA varB varC { 
    gen `v' = 42 
}

* core idea and verification
unab wanted : var* 
local wanted : subinstr local wanted "var" "", all

display "`wanted'"
A B C