Announcement

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

  • Local and Square Bracket Notation

    I am trying to create a loop where the new variable depends on year and row of the old variable. However if I use the row operator I get an error message. Without the row operator the code works fine. So I think it is the combination of subtracting a number in the name of a variable and the row operator.

    here is the code for the fool loop

    Code:
    foreach y of numlist 2000/2015{
    foreach n of numlist 0/17{
        replace newvar_`n'_`y'=oldvar_`y'-`n'[_n-`n']
    }
    }
    here is the code just for year 2000 that should help to understand what I am trying to do. I need to do that for years 2000-2015

    Code:
        replace newvar_0_2000 =oldvar_2000[_n-0]
        replace newvar_1_2000 =oldvar_1999[_n-1]
        replace newvar_2_2000 =oldvar_1998[_n-2]
        replace newvar_3_2000 =oldvar_1997[_n-3]
        replace newvar_4_2000 =oldvar_1996[_n-4]
        replace newvar_5_2000 =oldvar_1995[_n-5]
        replace newvar_6_2000 =oldvar_1994[_n-6]
        replace newvar_7_2000 =oldvar_1993[_n-7]
        replace newvar_8_2000 =oldvar_1992[_n-8]
        replace newvar_9_2000 =oldvar_1991[_n-9]
        replace newvar_10_2000=oldvar_1990[_n-10]
        replace newvar_11_2000=oldvar_1989[_n-11]
        replace newvar_12_2000=oldvar_1988[_n-12]
        replace newvar_13_2000=oldvar_1987[_n-13]
        replace newvar_14_2000=oldvar_1986[_n-14]
        replace newvar_15_2000=oldvar_1985[_n-15]
        replace newvar_16_2000=oldvar_1984[_n-16]
        replace newvar_17_2000=oldvar_1983[_n-17]

  • #2
    I think you want
    Code:
    foreach y of numlist 2000/2015{
        foreach n of numlist 0/17{
            replace newvar_`n'_`y'=oldvar_`=`y'-`n''[_n-`n']
        }
    }
    The sequence in your original code, `y'-`n' receives macro substitution and becomes, for example, 2000-3 (when `y' == 2000 and `n' == 3) as a string. But that syntax does not tell Stata to then evaluate 2000-3 as a numerical expression. The syntax I use here tells Stata to actually subtract the 3 from 2000 and create the result as 1997.

    Comment


    • #3
      Clyde Schechter thank you so much! It worked!

      Comment

      Working...
      X