Announcement

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

  • lagged variables in current variable function

    Question about lagged variables in stata

    Since the lagged variables won't autometically change to reflect the change in current varible, I'm wondering how to make it adaptive to the change of current variable, which can be a formula, instead of mannually updating it every time.


    For example, HAt= 0.1*roa1+0.9*HAt-1,
    I have to calculate HA (HistoricA).

    by gvkey year, sort: gen HistoricA =.
    by gvkey year, sort: gen HistoricA1 = HistoricA[_n-1]
    by gvkey: replace HistoricA1 = roa if _n == 1
    by gvkey: replace HistoricA = 0.1 * roa1 + 0.9 * HistoricA1 if _n > 1


    The above coding doesn't work. It gives me the result like :

    gvkey year roa roa1 roa2 HistoricA HistoricA1
    1004 1999 .0474536 . .0474536
    1004 2000 .0264029 .0474536 . .
    1004 2001 -.0829894 .0264029 . 0474536 .
    1004 2002 -.018074 -.0829894 . 0264029 .
    1004 2003 .0049401 -.018074 -. 0829894 .





    Is there any loop function or other codes could solve the automatically change problem?

    Appreciate your help in advance!
    Last edited by Zoey Gu; 29 Aug 2024, 14:53.

  • #2
    I don't know if I understand what you want. If you are wondering whether Stata can do something like the way an Excel spreadsheet can have a formula in a cell that will automatically update itself when some other cell mentioned in that formula changes, the answer is, no, Stata does not do that.

    But maybe you mean something simpler. Perhaps this is what you are looking for is to have Stata iteratively calculate the value of HistoricA in successive years in a fairly simple way using the recursion relationship you showed in #1. That you can do by something like this:
    Code:
    xtset gvkey year
    // NEED SOMETHING TO INITIALIZE THE VALUE OF HISTORICA IN FIRST YEAR FOR EACH GVKEY
    by gvkey (year): replace HistoricA = 0.1*L1.roa + 0.9*L1.HistoricA if _n > 1
    The problem is, from what you show, I don't know how to initialize the value of HistoricA in the first year. But if you do
    Code:
    by gvkey (year): gen HistoricA = something if _n == 1
    at that point, the second command will propagate everything down from there.

    To learn more about the L1 lag operator, and other time-series operators, read -help tsvarlist-.

    Comment


    • #3
      Thank you so much! It works perfectly and get what I want. Appreciate it!

      I suspect R would be able to finish this automatically change with single line of code. But I figured it with Python earlier before.

      Comment

      Working...
      X