Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Looping through (random) subsets of globals

    I have a global $countries that contains the names of N (sub-)directories (each directory is named according to a two letter country code). I would like to refer to the nth directory in my global - that is, I would like to index the entries in $countries somehow.

    Here is a minimal working example with N = 10:

    First, I create an example directory on my desktop using the "shell" command followed by the appropriate Bash code.

    Code:
    cd "desktop"
    shell mkdir -p EXAMPLE/{et,gh,ke,mg,mz,ni,ng,rw,sn,tz}
    cd "EXAMPLE"
    Next, I make a global macro $countries that contains the country codes. As you see, the global does not include delimiting characters (e.g. spaces or commas) between the country codes.
    Code:
    . global countries : dir "." dirs "*"
    . di $countries
    etghkemgmzningrwsntz
    I can loop through the countries without problems like so...

    Code:
    foreach country in $countries {
    di "...now working on `country'..."
    }
    What if I would like to run the loop for a subset of these countries? I tried the function "word()" but this fails because words in Stata should be delimited by spaces. Strangely enough it works for the first word but not for the remaining nine (here I try it for the 4th, which should return "mg" - but does not).

    Code:
    . global countries : dir "." dirs "*"
    
    . di word($countries, 1)
    et
    
    .
    
    . di word($countries, 4)
    
    
    .
    How can I refer to one or more of the items inside $countries, with the goal to loop through such a subset?
    The aim is to have something like this for, e.g., the 5th, 6th, 7th, 8th, 9th, and 10th country (this code is made up to show you what I mean conceptually - it does NOT work):

    Code:
    local subset word($countries , 5/10) // this obviously does not work!
    foreach country in `subset' {
    ...do something...
    }
    The ultimate idea is to use this for testing in a context where I have (many) more than 10 folders. Denoting the number of country directories as N, I would like to draw n < N integers without replacement from {1, 2, 3, 4, . . . , N } and loop through the respective n country directories.

    Thanks a lot in advance!

  • #2
    Note the double quotes:

    Code:
    global countries et,gh,ke,mg,mz,ni,ng,rw,sn,tz
    global countries: subinstr global countries "," " ", all
    di word("$countries", 3)
    Don't use globals unless you have to. Use locals instead.

    Res.:

    Code:
    . di word("$countries", 3)
    ke

    Comment

    Working...
    X