2

I have a Stata program that outputs a local scalar of space-separated variable names.

I have to run the program twice on two samples (same dta) and store the union (intersection - variable names appearing in both scalars) as a new space-separated local scalar (for input to another program).

I can't figure out how to split (per spaces) and or test the occurrences of variable names in each.

km5041
  • 351
  • 1
  • 4
  • 13
  • Being local and being scalar are different. A scalar can have a temporary name, which is not the same thing. EIther way, showing your code as well as explaining it is a good idea. – Nick Cox Oct 16 '17 at 23:22

2 Answers2

6

Stata has a bunch of extended macro functions to use on lists that you can find with help macrolists, where you can see that A & B returns the intersection of A and B. If A="a b c d" and B="b c f g", then A & B = "b c".

This allows you to do something like this:

clear
scalar l1="vara varb varc"
scalar l2="varc vard vare"
local l1 = scalar(l1)
local l2 = scalar(l2)
local inter: list l1 & l2
scalar inter="`inter'"
scalar list inter

You convert the scalars to locals, get their union, and convert that into a scalar. It is probably easier to just modify your code to use locals rather than scalars so you don't have to deal with conversions.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
dimitriy
  • 9,077
  • 2
  • 25
  • 50
0

I am not sure I perfectly understand your question, if this is not the appropriate answer, please add an example for us to work with.

Here is the code that checks two space-separated macros and gets their intersection, even if it's not the most elegant, unless your macros are huge it should still be quite fast.

local list1 first list here
local list2 list two here
local intersection 

foreach l1 in `list1' {
    foreach l2 in `list2' {
        // if they overlap, add to the intersection macro
        if "`l1'" == "`l2'" {
            local intersection `intersection' `l1'
        }
    }
}

mac list // show the macros stored currently in the do file
Eric HB
  • 867
  • 6
  • 17