Announcement

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

  • Forvalues operating as string?

    Hi folks, I'm looking to create successive Mantel–Haenszel estimate of rate ratios across various categories in a variable, each time comparing to the previous value.
    i.e.
    stmh agecat, c(1,0)
    stmh agecat, c(2,1)
    etc.

    I thought of doing this via a forvalues loop as such:

    forvalues x = 1/6 {
    stmh agecat, c(`x',`x'-1)
    }

    However as you can see in bold, for some reason the subtraction isn't being evaluated, and it's being concatenated as though a string and failing.

    Mantel–Haenszel estimate of the rate ratio
    comparing agecat==1 vs. agecat==1-1

    unknown el 1-1 in rule
    r(198);

    Out of interest, I tried to display `x'-1, but the math works there but the rest doesn't.

    forvalues x = 1/6 {
    display `x'-1
    stmh agecat, c(`x',`x'-1)
    }

    0

    Mantel–Haenszel estimate of the rate ratio
    comparing agecat==1 vs. agecat==1-1

    unknown el 1-1 in rule
    r(198);


    Any hints? Thanks!

  • #2
    for some reason the subtraction isn't being evaluated, and it's being concatenated as though a string
    The reason its being treated as a string is because, by definition, local macros are strings.

    You can, however, force evaluation of a local macro whose contents are a valid expression using the `=...' operator:

    Code:
    stmh agecat, c(`x',`=`x'-1')

    Comment


    • #3
      Hi Clyde, thank you! I had [mistakenly obviously] thought that using forvalues would be treated as a numeric (as opposed to foreach x...).
      Is there a reason here that
      Code:
      display `x'-1
      isn't treated as a string and outputs the numeric? The fact that these two steps worked differently is what threw me off.

      Comment


      • #4
        The context of a loop here is not material.

        The difference you see is that display faced with an expression including macros calculates the result of the expression and then displays the result. Otherwise all that happens with your code is that macros are evaluated automatically—their names are replaced with their contents—but there is no calculation of expressions unless you insist on that with specific syntax.

        Comment


        • #5
          And let me add to Nick's spot-on observation that what -display- is doing has nothing to do with macros. -display- will evaluate any expression, whether it contains macros or not, and display the result unless that expression is bound in quotes. This is a property of the display command.
          Code:
          . local x 3
          
          . display `x'+1
          4
          
          . display 3+1
          4
          
          . display "3+1"
          3+1

          Comment


          • #6
            Excellent, thanks both!

            Comment

            Working...
            X