title: Fama MacBeth regression in R
body: <p>I am trying to do Fama Macbeth regression on some tradable factors using 5-year rolling window updated monthly. </p>
  
  <p>I have the data of excess returns of 1000 stocks and the data of certain risk factors from July 1997 and December 2014.</p>
  
  <p>However, I am very new to R and don't know how to deal with it correctly.</p>
  
  <p>I have saw an example before. However it didn't involve rolling. Besides, I don't know how to get Newey-West t-statistic. </p>
  
  <pre><code>library(foreign)
  test&lt;-read.dta("http://www.kellogg.northwestern.edu/faculty/petersen/htm/papers/se/test_data.dta")
  num=500; T=10;
  #step1: 500 time-series regressions
  betas &lt;- matrix(nrow=num, ncol=2)
  colnames(betas) &lt;- c("Intercept", "beta")
  for (i in 1:num) {
    betas[i,] &lt;- coef(lm(y~x, test[test$firmid==i,]))
  }
  test$betas &lt;- rep(betas[,2],each=T)
  #step2: 10 cross-section regressions
  factor_premia &lt;- matrix(nrow=T)
  colnames(factor_premia) = "Ret_Premium"
  for (j in 1:T) {
    factor_premia[j] &lt;- coef(lm(y~betas, test[test$year==j,]))[2]
  }
  factor_risk_premia &lt;- mean(factor_premia)
  </code></pre>
  
  <p>Any help or suggestions will be greatly appreciated.</p>