Announcement

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

  • String in Local inside another Local

    I need to place a local inside another local and have a string inside these two locals. Something like this:

    Code:
    sysuse auto
    local brand="Subaru"
    local restrict = " if make == "`brand'" "
    sum turn `restrict'
    I get an error invalid syntax. If I remove quotations around brand then I get Subaru not found. any help would be greatly appreciated.

  • #2
    Well, the syntax error you are getting arises from the impossibility of parsing quotes when used as in your -local restrict = ...- command. Do you mean
    Code:
    local restrict = " if make == "             `brand'          " "
    Or are the quotes supposed to be nested, which would require the use of compound double quotes:
    Code:
    local restrict = `"if make == "`brand'" "'
    You cannot nest ordinary quotes because of this inherent ambiguity in interpretation.

    That said, you are overusing quotes and = anyway. Wrapping the definition of a local macro in outer quotes is usually pointless, because Stata strips them automatically. It should be done only if you need to preserve an initial quote in the content you wish to place in the local macro. And also the use of = is necessary only if you want the expression on the right side to be evaluated, rather than copied into the macro. But when the right side is a simple string, it makes no difference and the evaluation is just wasted effort.

    I believe what you are trying to do can be done as follows:
    Code:
    sysuse auto, clear
    local brand Subaru
    local restrict if make == "`brand'"
    sum turn `restrict'
    Last edited by Clyde Schechter; 17 Feb 2025, 08:49.

    Comment


    • #3
      Clyde Schechter covers all the major points and some of the minor points.

      Here is another minor point.

      Code:
      local restrict = Subaru 
      instructs Stata to evaluate the expression after the equals sign and put the result in the local macro restrict. Here Subaru could be the name of a variable, but there is no such variable, or it could be the name of a scalar. but there is no such scalar. Hence Stata reports not being able to find Subaru.

      Incidentally, if Subaru had been the name of a variable, Stata would have used Subaru[1] in evaluation.

      If you go

      Code:
      local restrict Subaru
      there is no evaluation, just copying of content.

      Code:
      local restrict "Subaru"
      is legal always, for the same kind of reason.

      "Subaru" is just literal text and Stata doesn't check for it being or referring to anything else.

      Comment

      Working...
      X