title: R - use group_by() and mutate() in dplyr to apply function that returns a vector the length of groups
body: <p>Take the following example data:</p>
  
  <pre><code>set.seed(1)
  
  foo &lt;- data.frame(x=rnorm(10, 0, 10), y=rnorm(10, 0, 10), fac = c(rep("A", 5), rep("B", 5)))
  </code></pre>
  
  <p>I want to split the dataframe "foo" by the variable "fac" into A's and B's, apply a function (mahalanobis distance) that returns a vector of the length of each subgroup, and then mutate the output back on to the original dataframe. For example:</p>
  
  <pre><code>auto.mahalanobis &lt;- function(x) {
    temp &lt;- x[, c("x", "y")]
    return(mahalanobis(temp, center = colMeans(temp, na.rm=T), cov = cov(temp, 
  use="pairwise.complete.obs")))
  }
  
  foo %&gt;% group_by(fac) %&gt;%
    mutate(mahal = auto.mahalanobis(.))
  </code></pre>
  
  <p>Which gives an error. Obviously this procedure can be done manually by splitting the dataset, applying the function, and adding the output as a column before putting it all back together again. But there must be a more efficient way to do this (perhaps this is a misuse of dplyr?).</p>