Announcement

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

  • Calculate annual changes via loops

    Good morning
    I would like to report a series of annual variations using a loop.
    This is my initial situation:
    Code:
    gen TOTIMMOVAR2015=(TOTIMMO2015-TOTIMMO2014)/abs(TOTIMMO2014)
    *
    gen TOTIMMOVAR2016=(TOTIMMO2016-TOTIMMO2015)/abs(TOTIMMO2015)
    *
    gen TOTIMMOVAR2017=(TOTIMMO2017-TOTIMMO2016)/abs(TOTIMMO2016)
    *
    gen TOTIMMOVAR2018=(TOTIMMO2018-TOTIMMO2017)/abs(TOTIMMO2017)
    *
    gen TOTIMMOVAR2019=(TOTIMMO2019-TOTIMMO2018)/abs(TOTIMMO2018)
    My goal (as an assignment for the university) is to report this code in the form of a loop.
    To do this I thought up this code:
    Code:
    local Year1=2015
    local YearN=2019
    forvalues y=`Year1'(1)`YearN'  {
        gen TOTIMMOVAR`y'=(TOTIMMO[`y']-TOTIMMO[`y'-1])/abs(TOTIMMO[`y'-1])
    }
    But unfortunately it doesn't work.
    Thank you in advance for any help or suggestions!

  • #2
    The notation var[subscript] refers to the subscript'th observation's value of var. So TOTIMMO[2015] is not the variable TOTIMMO2015. It is the value of TOTIMMO in observation #2015 in the data set.

    The command inside the loop needs the values of `y' and `y'-1 to be directly written after TOTIMMO, not in brackets.

    Code:
    gen TOTIMMOVAR`y' = (TOTIMMO`y' - TOTIMMO`=`y'-1')/abs(TOTIMMO`=`y'-1'
    That said, this loop is a suboptimal way to do this. This kind of thing is best done with the data in long layout, and it does not require a loop.

    Code:
    gen long obs_no = _n
    reshape long TOTIMMO, i(obs_no) j(year)
    xtset obs_no year
    gen TOTIMMOVAR = D1.TOTIMMO/abs(L1.TOTIMMO)
    And if there is reason to return to the original wide layout you can follow that with -reshape wide TOTIMMO TOTIMMOVAR, i(obs_no) j(year)-

    Comment


    • #3
      Originally posted by Clyde Schechter View Post
      The notation var[subscript] refers to the subscript'th observation's value of var. So TOTIMMO[2015] is not the variable TOTIMMO2015. It is the value of TOTIMMO in observation #2015 in the data set.

      The command inside the loop needs the values of `y' and `y'-1 to be directly written after TOTIMMO, not in brackets.

      Code:
      gen TOTIMMOVAR`y' = (TOTIMMO`y' - TOTIMMO`=`y'-1')/abs(TOTIMMO`=`y'-1'
      That said, this loop is a suboptimal way to do this. This kind of thing is best done with the data in long layout, and it does not require a loop.

      Code:
      gen long obs_no = _n
      reshape long TOTIMMO, i(obs_no) j(year)
      xtset obs_no year
      gen TOTIMMOVAR = D1.TOTIMMO/abs(L1.TOTIMMO)
      And if there is reason to return to the original wide layout you can follow that with -reshape wide TOTIMMO TOTIMMOVAR, i(obs_no) j(year)-
      Thanks again for your availability. Your help is really precious!

      Comment

      Working...
      X