Announcement

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

  • Moving average of lagged values in panel data

    Dear forum users,

    I am working on a panel dataset where country is the cross-sectional unit and year the time dimension. Let me call the variable of interest X. My goal is to calculate country specific means of different window sizes. For instance, for the year 2000 in the Netherlands, I would like to calculate the Netherlands specific mean of X during the years 1996 - 2000 for a 5 year window, or the mean of the years 1991 - 2000 for a 10 year window, etc. There are no missing values. Can someone help me with this?

    Thank you very much in advance!

    ps: I tried to simplify the context but please let me know if more information is needed.

  • #2
    Welcome to Stata list. You will increase your chances of useful answer by providing Stata code in code delimiters, readable Stata output, and sample data using dataex.

    Knowing the exact structure of your data is essential to helping you really. If you have panel data, then you need to xtset your data. If you xtset your data, you can refer to previous values with lags. So the mean of the previous five values could be
    g m=(L.x+ L2.x + L3.x + L4.x+L5.x)/5

    There are more efficient ways to program it but this is an easy way to understand for a beginner.

    Comment


    • #3
      You can also try asrol for various rolling window statistics.
      Code:
      ssc install asrol
      help asrol
      
      *some examples
      
      *Example 1: Find the arithmetic mean in a rolling window of 4 observations for each group (company)
       
          . webuse grunfeld
       
          bys company: asrol invest, stat(mean) win(year 4)
      
          *This command calculates the arithmetic mean for the variable invest using a four years rolling window and stores the results in a new variable, mean4_invest.
      
      *Example 2: Geometric mean in a rolling window of 10
       
          . webuse grunfeld
       
          bys company: asrol invest, stat(gmean) win(year 10)
      Regards
      --------------------------------------------------
      Attaullah Shah, PhD.
      Professor of Finance, Institute of Management Sciences Peshawar, Pakistan
      FinTechProfessor.com
      https://asdocx.com
      Check out my asdoc program, which sends outputs to MS Word.
      For more flexibility, consider using asdocx which can send Stata outputs to MS Word, Excel, LaTeX, or HTML.

      Comment

      Working...
      X