0

I have lists of variables in local macros that I would like to use in a command, e.g.:

    local a int1 int2 num1 num2 bin1 bin2 ...
    local b int3 int4 bin3 num3  ...

Here variable num* int* and bin* are numeric, integer and binary respectively.

I want to run a foreach loop over of the variables in local a' and b', but only those that are integer-valued, namely, int1, int2, int3, ...

For this, I use findname command created by Nick Cox to find variables that are integer-valued, saving a list of corresponding variable names in a local macro. But I do not want to run it for all variables in a dataset but only for subsets of variables (designated in locals a, b, and so on), and then use the list in a subsequent command.

So for a list of integer variables in local a' and b' being local a_int' and b_int', I want to use is as below:

    foreach var of varlist `a_int' `b_int'{
        whatever command
    }
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
Makiko
  • 27
  • 9
  • 1
    Well, if `foo` is in a list you can create a new variable `foo_qualifies` as `gen foo_qualifies = 1` which is 1 in all observations. And so on for other variables. I can't see why that is any use over and above what `findname` provides. Why do you want this? – Nick Cox Jan 26 '21 at 10:38
  • @Makiko What would you want your indicator variable to be if you have, let's say, two variables x1 and x2, and one observation where x1 = 1, x2=3.5? I think your question would benefit from a minimal example of your data together with your wanted output. See also the [Stata tag wiki](https://stackoverflow.com/tags/stata/info) for info on how best to ask questions. – Wouter Jan 26 '21 at 14:53

1 Answers1

1

If I understand you correctly, you need the intersection of two lists stored in local macros. To do this you can use the macro extended functions to manipulate lists: see help macrolists.

// Setup
local a x1 x2 x3 x4 x5
local b x4 x5 x6 x7 x8
local int x2 x3 x6

// Get intersection of variable lists and integer list
local a_int : list a & int
local b_int : list b & int

// Put a_int and b_int together and drop possible duplicates
local ab_int `a_int' `b_int'
local ab_int_uniq : list uniq ab_int

// Do something
foreach var of varlist `ab_int_uniq' {
    * do something
}
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
Wouter
  • 3,201
  • 6
  • 17