Search code examples
statastata-macros

Looping over many names which don't have rules


When there are just few names, looping in Stata is easy.

Also, when there is a rule as to how the names change (e.g. increment) I can do the following:

forval i = 1/5 {
    ...
}

However, there are cases where i have hundreds of names that I need to loop over, which don't have rules of increment.

For example:

48700 48900 48999 49020 49180 49340 ...

Is there some short-hand way of writing the loop? Or do I just have to painstakingly list all of them?


Solution

  • The answer is it depends.

    If these are part of variable names, you can do something like this:

    clear
    set obs 5
    
    foreach var in 48700 48900 48999 49020 49180 49340 {
        generate var`var' = runiform()
    }
    
    ds
    var48700  var48900  var48999  var49020  var49180  var49340
    
    ds var48*
    var48700  var48900  var48999
    
    local names `r(varlist)'
    
    foreach var of local names {
        display `var'
    }
    
    .41988069
    .06420179
    .36276805
    

    If these are file names, a macro extended function can be handy:

    dir, w
    
    48700.rtf       48999.rtf       49180.rtf
    48900.rtf       49020.rtf       49340.rtf
    
    local list : dir . files "*"
    display `list'
    48700.rtf48900.rtf48999.rtf49020.rtf49180.rtf49340.rtf
    
    local list : dir . files "48*"
    display `list'
    48700.rtf48900.rtf48999.rtf
    
    foreach fil of local list {
        display "`fil'"
    }
    48700.rtf
    48900.rtf
    48999.rtf
    

    EDIT:

    The above approaches are concerned with how to efficiently get all relevant names in a local macro.

    If you already know the names and you merely want a cleaner way to write the loop (or want to re-use the names in several loops), you can simply assign these in a local macro yourself:

    local names var48700 var48900 var48999 var49020 var49180 var49340
    
    foreach var of local names {
        display `var'
    }
    
    .41988069
    .06420179
    .36276805
    .52763051
    .16493952
    .66403782
    

    The local macro names will automatically expand during run time to include all the specified items.