Announcement

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

  • How to create variable names that calls a local macro containing a string?

    Hi,

    I am trying to create variable names by calling a local macro that contains a string, but the quotes in the macro breaks the code. I know that I am mixing up macros and variables names but is there a work around this? The following is a reproducible piece of code that illustrates my problem:

    Code:
    webuse auto, clear
    decode foreign, gen(type)
    
    // The following will work:
    
    forvalues i = 0/1 {
        reg price mpg if foreign == `i'
        gen b`i' = _b[mpg]
    }
    
    // But is there a work around for the following:
    
    forvalues i = 0/1 {
        levelsof type, local(type_name)
        reg price mpg if foreign == `i'
        gen `type_name' = _b[mpg]
    }
    Thank you for your help.

    Best,
    ​Aaditya

  • #2
    I think you need to give us a clearer explanation of what you are trying to do. There is no variable named type in the auto data set, so -levelsof- will complain and stop you cold right there. Even if there were, repeatedly doing -levelsof- inside the loop makes no sense, as it just does the exact same thing every time. And, even disregarding that, the local macro type_name it creates would create a list of several words: one word corresponding to each value taken on by the (hypothetical) variable type. But the syntax of -gen- only allows for a single variable name before the equal sign.

    So if you can explain what you want to do, I'm sure we can figure it out.

    Comment


    • #3
      Hi Aaditya

      Try the following

      Code:
      levelsof type, local(type_name)
      foreach i of local type_name {
          reg price mpg if type == "`i'"
          gen `i' = _b[mpg]
      }
      Abraham

      Comment


      • #4
        A nearly reproducible example is better than none at all, but it's still unclear what you're trying to do. Only exceptionally will value labels be suitable as variable names, as anything over-length or otherwise violating the rules on variable names will fail. Nor is it usually a good idea to create separate variables for the constants from several model fits.

        Comment


        • #5
          Thank you everyone. Abraham: your solution was exactly what I was looking for. Also, just to clarify: I was trying to generate new variables that take on different names, based on some string variables that have been assigned to a local macro. (The context in which I was trying to do this was very different from the code I posted; the code was just for illustration purposes. I will keep your suggestions in mind as well. Thanks once again.)

          Comment

          Working...
          X