title: How to run the same code on multiple different datasets in R
body: <p>I am trying to run a series of fixed effects linear regressions on six different sets of data. For each dataset, I would like to run the regression multiple times on subsets of the data.</p>
  
  <p>I have developed code to do this once, for one dataset. But I would like to write generic code, so that I can run this for each of the six separate sets of data. </p>
  
  <p>This is what I have so far using an example dataset:</p>
  
  <pre><code>month &lt;- (rep(0:35, 36))
  monthfact &lt;- as.factor(month)
  prodid2&lt;- as.character(rep(112:147, 36))
  log_value &lt;- rnorm(1296)
  exp_share &lt;- abs(rnorm(1296))
  regdat &lt;- data.frame(month, monthfact, prodid2, log_value, exp_share)
  #Subset the data into 24 datasets, each of which includes a 13 month window
  subfun&lt;-function(x,y,z) {  subset(x,y&gt;=z &amp; y&lt;=z+12)}
  dsets &lt;- lapply(1:24, function(x) subfun(regdat, regdat$month, x-1)) 
  #Writing a function for running linear regressions
  
  lmfun&lt;-function(data){  lm(log_value~monthfact+prodid2, data = data, 
  weights = data$exp_share)}
  #Apply the function to all the datasets in the list
  linreg&lt;-lapply(dsets,lmfun)
  coefs&lt;-lapply(linreg,coef)
  #Choose only the coefficients for month 
  coefs &lt;- as.data.frame(lapply(coefs, function(x) {x[2:13]}))
  #Add in a row of 0 values for the baseline month
  baseline&lt;-rep(0,each=24)
  coefs&lt;-rbind(baseline,coefs)
  
  #Compute the index using the dataframe created
  FEindexes&lt;-data.frame(lapply(coefs, function(x) (exp(x))/(exp(x[1]))))
  splices&lt;-FEindexes[2,]
  splices &lt;- apply(splices, 1, cumprod)
  splices &lt;- c(1,splices[1:23])
  FEindex13&lt;-t(FEindexes[13,])
  FEWS&lt;-splices*FEindex13
  FEWS&lt;-as.data.frame(FEWS[2:24])
  firstFEWS&lt;-as.data.frame(FEindexes[,1])
  colnames(firstFEWS) &lt;- "FEWS_index"
  colnames(FEWS) &lt;- "FEWS_index"
  FEWS&lt;-rbind(firstFEWS,FEWS)
  View(FEWS)
  </code></pre>
  
  <p>I would like to run all of this code on 6 different datasets, and wondered if there's a way to do this in R without having to re-run all the code 6 times?</p>
  
  <p>Thanks very much for your help.</p>