Announcement

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

  • Loop through a string list (not a variable list)

    Hi,

    I would like to loop through a list of strings to fill in a string variable with a condition. Basically, to a number "n" correspond a country 3 letter name. I know how to loop through variables but I'm struggling with strings.

    Code:
    sysuse auto, clear
    
    bys rep78: gen n=_n
    gen country = .
    
    * These are strings (not variables)
    local var "AUD BEF CAD CHF DEM DKK EUR FRF GBP ITL JPY NLG NOK NZD SEK"
    display "`var'"
    
    local n: word count `var'
    forvalues i = 1/`n' {
        local v1 : word `i' of "`var'"
        replace country = "`v1'" if n==`i'
    }
    Note that I am not interested in other methods to do achieve this goal. I'd like to learn how to loop through strings for future reference! Thanks!

  • #2



    A bug in your code is that you initialise country as numeric missing and then try to overwrite those missings with string values.

    This should be closer to correct:

    Code:
    sysuse auto, clear  
    bys rep78: gen n=_n
    gen country = ""  
    local var "AUD BEF CAD CHF DEM DKK EUR FRF GBP ITL JPY NLG NOK NZD SEK"
    display "`var'"
    tokenize "`var'"  
    local n: word count `var'  
    forvalues i = 1/`n' {    
        replace country = "``i''" if n==`i'
    }

    Comment


    • #3
      Well, for one thing you need to get rid of the double quotes in

      Code:
      local v1 : word `i' of "`var'"
      as they cause var to contain exactly one word: "AUD BEF CAD ..."

      As you explicitly ask us to not further comment on your approach, I will not do so.

      Best
      Daniel

      Comment

      Working...
      X