Announcement

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

  • using i and i+1 in variable names as part of a forval loop

    In a forval loop I want to reference both variable r`i'name and r`j' name, where j is a function of i.
    where `j' = `i' + 1

    but r`j' name invariably comes back as r[ival]+1name

    specifically I run:

    forval i=12(-1)1 {
    local j = `i'+1
    replace r`i'name = r`j'name if r`i'name_t == 0
    }

    and I get back a trace report that reads:
    = replace r12name = r12+1name if r12name_t == 0
    r12 ambiguous abbreviation

    this is because I believe that Stata cannot process the relative value withing a variable name - the program does not do math in these places...
    -1- is there a way for me to define both {i, j} up top - is there some way to use an ampersand or other such ting to set a counter for j along with i ahead of the open set bracket?
    -2- other ideas welcome as well.

    Thank you,
    Jason Seligman

  • #2
    What you post looks good to me, so I have to ask if it is exactly what you tried. In particular, using “ “ in the definition of local j would produce the error you report.

    Comment


    • #3
      Will this work?

      Code:
      forval i = 12(-1)1 {
            scalar add = `i' + 1
            local j = add
            replace r`i'name = r`j'name if r`i'name_t == 0
      }
      Alfonso Sanchez-Penalver

      Comment


      • #4
        Following up on Nick's clue, here's an example that demonstrates that you apparently omitted the "=" from the local j command that you actually ran.
        Code:
        . forval i=12(-1)9 {
          2.     local j = `i'+1
          3.     display `"  correct: r`i'name = r`j'name if r`i'name_t == 0 "'
          4.     local j `i'+1
          5.     display `"incorrect: r`i'name = r`j'name if r`i'name_t == 0 "'
          6. }
          correct: r12name = r13name if r12name_t == 0
        incorrect: r12name = r12+1name if r12name_t == 0
          correct: r11name = r12name if r11name_t == 0
        incorrect: r11name = r11+1name if r11name_t == 0
          correct: r10name = r11name if r10name_t == 0
        incorrect: r10name = r10+1name if r10name_t == 0
          correct: r9name = r10name if r9name_t == 0
        incorrect: r9name = r9+1name if r9name_t == 0
        
        .

        Comment


        • #5
          At this point I favour the guess of William Lisowski rather than mine. The point is that the syntax in #1 is good, so that (we have to believe that) you must have typed something else.

          (There is no need for any kind of work-around using a scalar.)

          Comment

          Working...
          X