title: Moving average using forvalues - Stata
body: <p>I am struggling with a question in Cameron and Trivedi's "Microeconometrics using Stata". The question concerns a cross-sectional dataset with two key variables, log of annual earnings (lnearns) and annual hours worked (hours).</p>
  
  <p>I am struggling with part 2 of the question, but I'll type the whole thing for context. </p>
  
  <p>A moving average of y after data are sorted by x is a simple case of nonparametric regression of y on x. </p>
  
  <ol>
  <li>Sort the data by hours.</li>
  <li>Create a centered 15-period moving average of lnearns with ith observation yma_i = 1/25(sum from j=-12 to j=12 of y_i+j). This is easiest using the command forvalues. </li>
  <li>Plot this moving average against hours using the twoway connected graph command. </li>
  </ol>
  
  <p>I'm unsure what command(s) to use for a moving average of cross-sectional data. Nor do I really understand what a moving average over one-period data shows.</p>
  
  <p>Any help would be great and please say if more information is needed. 
  Thanks!</p>
  
  <p>Edit1: </p>
  
  <p>Should be able to download the dataset from here <a href="https://www.dropbox.com/s/5d8qg5i8xdozv3j/mus02psid92m.dta?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/5d8qg5i8xdozv3j/mus02psid92m.dta?dl=0</a>. It is a small extract from the 1992 Individual-level data from the Panel Study of Income Dynamics - used in the textbook. </p>
  
  <p>Still getting used to the syntax, but here is my attempt at it</p>
  
  <pre><code>sort hours
  gen yma=0 
  1. forvalues i = 1/4290 {
  2. quietly replace yma = yma + (1/25)(lnearns[`i'-12] to lnearns[`i'+12]) 
  3. }
  </code></pre>