Announcement

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

  • Removing Compound Quotes in Local Macro

    I am using levelsof to feed a list of ISO-3 country codes into wbopendata to query countries' GDP from the World Bank. wbopendata requires that the list of countries to be queried is in this format:

    Code:
    "ABW;AFG;ALB;ANT"
    levelsof gives me an output like this:

    Code:
    `"ABW"';`"AFG"';`"ALB"';`"ANT"'
    I use subinstr() to remove the quotes:

    Code:
    local countries = `"`"ABW"';`"AFG"';`"ALB"';`"ANT"'"'
    di `"`countries'"'
    local countries = subinstr(`"`countries'"', `"""', "", .)
    di `"`countries'"'
    I receive the following result:

    Code:
    . local countries = `"`"ABW"';`"AFG"';`"ALB"';`"ANT"'"'
    
    . di `"`countries'"'
    `"ABW"';`"AFG"';`"ALB"';`"ANT"'
    
    . local countries = subinstr(`"`countries'"', `"""', "", .)
    
    . di `"`countries'"'
    ;;;
    which is not what I want. Am I having this issue because of all the compound quotes? I believe I am specifying correctly but clearly that is not the case.

  • #2
    Code:
    clear*
    set obs 4
    gen country = "ABW" in 1
    replace country = "AFG" in 2
    replace country = "ALB" in 3
    replace country = "ANT" in 4
    
    levelsof country, local(countries) clean separate(;)
    local countries `""`countries'""'
    
    macro list _countries

    Comment


    • #3
      Thank you, Clyde! I should have read the help for levelsof() first.

      Is there any reason why the approach I took - to substitute out the quotes from the full string - did not work? I was following the examples posted on Statalist for removing quotes from string variables. I was surprised that it substituted out the entire contents of the quotes and just left the semicolons.

      Comment


      • #4
        Is there any reason why the approach I took - to substitute out the quotes from the full string - did not work?
        Yes. That subinstr() function removed all of the " characters from local countries. At first brush that would leave:
        Code:
        `ABW';`AFG';`ALB';`ANT'
        But now this entire thing looks to Stata like the contents of a string containing four local macros, `ABW;`AFG;`ALB';`ANT'. So those local macros now have to be expanded. But there are no local macros with names ABW, AFG, ALB, and ANT defined. So all of those are empty strings and we are left with just ;;; , which is just what Stata gave you. You were, in effect, giving Stata credit for figuring out what you meant to do in removing quotes. But Stata just took you literally.

        Comment

        Working...
        X