Announcement

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

  • String variable in Do-file

    Noob question:

    I need to use a string variable in the name of other variables. I thought of something like:

    gen country="EU"
    gen netexport_"country"=ex_"country" - im_"country"

    It is just an example to illustrate my problem. A loop would be sub-optimal.

  • #2
    Your first statement is legal. But if a new variable country contains "EU" in every observation it doesn't serve any purpose and bloats the dataset unnecessarily.

    Your second statement is illegal, but I can't work out precisely what you want. Exports and imports surely always involve two countries....

    As always, giving a concrete data example would help mightily. Please read and act on https://www.statalist.org/forums/help#stata

    Comment


    • #3
      I know that the second statement is illegal. What I want is that the entered string from the variable country is used in the second command.

      Comment


      • #4
        I can't add more without more explanation.

        Comment


        • #5
          Welcome to Statalist.

          Perhaps what you want is not a "variable" at all, but rather a local macro.
          Code:
          local country EU
          generate netexport_`country' = ex_`country' - im_`country'
          and perhaps you ultimately want to loop over a list of countries
          Code:
          foreach country in EU US China {
              generate netexport_`country' = ex_`country' - im_`country'
          }
          and perhaps one of your variables contains country codes and you want to loop over each of the country codes in your dataset
          Code:
          levelsof countrycode, local(countries)
          foreach country of local countries {
              generate netexport_`country' = ex_`country' - im_`country'
          }
          To learn more about these commands, see the output of
          Code:
          help local
          help foreach
          help levelsof
          Lacking a sample of your data, none of the code above has been tested.

          Comment

          Working...
          X