title: Fitting (multlple) linear models by group in R
body: <p>I'm trying to (somewhat) elegantly fit 3 models (linear, exponential and quadratic) to a dataset with classes/factors and save p-values and R2 for each model and class/factor.  Simple dataset with 3 variables: x,y, and class.  What I can't figure out is how to force each of the 3 models to fit to each of the 3 classes.  What I have now fits each model to the complete dataset.  The next question is how I then output p-values &amp; R2 to a table, for each model+class</p>
  
  <p>My code looks like:</p>
  
  <pre><code>set.seed(100)
  library(plyr)  
  #create datast
  nit &lt;- within(data.frame(x = 3:32),
                   {
                     class &lt;- rep(1:3, each = 10)
                     y &lt;- 0.5 * x* (1:10) + rnorm(30)
                     class &lt;- factor(class)                 # convert to a factor
                   }
                   )
  x2&lt;-nit$x*nit$x #for quadratic model
  forms&lt;- paste(c("y ~ x", "y ~ x+x2", "log(y) ~ x"), sep = "") # create 3 models
  names(forms) &lt;- paste("Model", LETTERS[1:length(forms)])
  models &lt;- llply(forms, lm, data = nit)
  models                # shows coefficients for each of the 3 models
  </code></pre>