Announcement

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

  • Creating lags of many variables all at once

    How can I efficiently create new variables for lags of many variables in my dataset?
    Say for example that I have the variables: cons inv out ae exp rev int oph lpt , and I do not want to create lags for each one separately (such as gen lag_cons=lag.cons, etc.) because it will take time especially if I have to do that for nearly 20 variables...

    I tried :
    Code:
    local X cons inv out ae exp rev int  oph lpt
    gen lag`X'=lag.`X'
    But I get error message that lag operator is invalid.

  • #2
    Hi Mike
    First. the operator is not "lag" but simply "l." or "L.". see "help tsvarlist"
    Second, why do you need to create the lags? Stata may do a better job tracking that when estimating your model.
    Third. still need to create the variables one by one, but you can use a loop.
    HTH
    Fernando

    Comment


    • #3
      Stata is correct. The operator is L. See

      Code:
      help varlist

      I am surprised that you didn't get another error message, as the left-hand side of your second command is illegal even before generate gets to look at lag.

      If you really need new variables, you need an explicit loop.

      Code:
      local X cons inv out ae exp rev int  oph lpt  
      foreach x of local X {      
          gen lag`x' = l.`x'
      }
      More commonly Stata just lets you specify lags on the fly when it is necessary. For example,


      Code:
      . webuse grunfeld, clear
      
      . tsset
             panel variable:  company (strongly balanced)
              time variable:  year, 1935 to 1954
                      delta:  1 year
      
      . regress invest L.invest year
      Last edited by Nick Cox; 20 Mar 2020, 06:39.

      Comment


      • #4
        Thanks Both.
        Sorry the lag in my code was obviously an typo from me. Sorry for that.
        Also, yes I understand that using L. will be fine but I do need the new lag variables to perform other tests that need them to be defined.
        Thanks a lot Nick, I will use this loop.
        Regards

        Comment

        Working...
        X