title: adding custom function to summarise in dplyr
body: <p>I have a data frame like this, with different observations for each <code>id</code>:</p>
  
  <pre><code>library(dplyr)
  df &lt;- data.frame(id=c(1,1,1,1,1,2,2,3), v1= rnorm(8), v2=rnorm(8))
  </code></pre>
  
  <p>I then group by <code>id</code>:</p>
  
  <pre><code>by_id &lt;- group_by(df, id)
  </code></pre>
  
  <p>Now I want to calculate mean and sd of the observations of <code>v1</code> for each <code>id</code>. This is easy with <code>summarise</code>:</p>
  
  <pre><code>df2 &lt;- summarise(by_id,
                      v1.mean=mean(v1),
                      v1.sd=sd(v1))
  </code></pre>
  
  <p>Now I want to add the slope of a linear regression of <code>v1</code> and <code>v2</code></p>
  
  <pre><code>df2 &lt;- summarise(by_id,
                     v1.mean=mean(v1),
                     v1.sd=sd(v1),
                     slope=as.vector(coef(lm(v1~v2,na.action="na.omit")[2])))
  </code></pre>
  
  <p>However, this fails, I think because one person (id=3) has only one observation and thus cannot build a linear model.</p>
  
  <p>I also tried</p>
  
  <pre><code>   slope=ifelse(n()==1,0,as.vector(coef(lm(v1~v2,na.action="na.omit")[2]))))
  </code></pre>
  
  <p>but it does not work either. Is there an easy solution for this?</p>
  
  <p>Not that it may also be the case that if I have more than one observation but for example <code>v2</code> has a missing value, so the <code>lm</code> might also fail.</p>