title: Linear model within a loop (loop used to subset data)
body: <p>I have (what I think should be) a straight forward problem in R, and can't seem to get it to work. Hope you can help.</p>
  
  <p>I have a data frame e.g.:</p>
  
  <pre><code>x  y  z
  1  2  a
  2  3  a
  3  4  a
  4  5  b
  5  6  b
  6  7  b      etc...
  </code></pre>
  
  <p>And I'm fitting a linear model (y ~ x) for each z value subset (e.g. a, b...) and extracting the gradient.</p>
  
  <p>It works when I select 'a' using a with statement as such:</p>
  
  <pre><code>coef(with(subset(data.frame, z == "a"), {lm(y ~ x)
  }))[2]
  </code></pre>
  
  <p>But my problem is that I have more than 1000 unique values in the Z column. So I tried to set up a loop (I know R users hate loops!) to do this for each value of z in turn and return the result in a data frame. Code is:</p>
  
  <pre><code>gradient.lm = NULL
  
  unique.z &lt;- as.matrix((unique(data.frame$z)))
  count.z &lt;- nrow(unique.z)
  
  for (i in 1:count.z) {
    gradient.lm[i] = coef((with(subset(data.frame, z == [i]), {lm(y ~ z)
    })))[2]
  }
  </code></pre>
  
  <p>But this is not working, and giving me the error code:</p>
  
  <pre><code>&gt; for (i in 1:count.z) {
  +   activity.lm[i] = coef((with(subset(data.frame, z == [i]), {lm(y ~ x)
  Error: unexpected '[' in:
  "for (i in 1:count.z) {
    activity.lm[i] = coef((with(subset(data.frame, z == ["
  &gt;   })))[2]
  Error: unexpected '}' in "  }"
  &gt; }
  Error: unexpected '}' in "}"
  </code></pre>
  
  <p>My guess was that it doesn't realise that there is an [i] within the with function.</p>
  
  <p>I can't find a way of making this work, or think of another way of doing it. If you have any suggestions they would be hugely appreciated.</p>