title: R: applying a function over a group
body: <p>I am looking to apply a function to a data frame and then store the results of that function in a new column in the data frame.  </p>
  
  <p>Here is a sample of my data frame, tradeData:  </p>
  
  <pre><code>Login   AL  Diff
      a   1   0
      a   1   0
      a   1   0
      a   0   1
      a   0   0
      a   0   0
      a   0   0
      a   1   -1
      a   1   0
      a   0   1
      a   1   -1
      a   1   0
      a   0   1
      b   1   0
      b   0   1
      b   0   0
      b   0   0
      b   1   -1
      c   1   0
      c   1   0
      c   0   1
      c   0   0
      c   1   -1
  </code></pre>
  
  <p>Where the "Diff" column is the column I am trying to add. It just just the difference between the values row(x-1) and row(x) of tradeData, grouped by Login.</p>
  
  <p>Here are some samples of what I've tried:  </p>
  
  <pre><code>tradeData$Diff = ave(tradeData$AL,tradeData$Login,FUN = function(x) {diff(x)}) 
  </code></pre>
  
  <p>and </p>
  
  <pre><code>tradeData$Diff = as.data.frame(with(tradeData,tapply(AL,Login,FUN = diff)))
  </code></pre>
  
  <p>I've found the following question useful thus far: <a href="https://stackoverflow.com/questions/19261159/r-applying-a-function-to-a-subset-of-a-data-frame">R applying a function to a subset of a data frame</a> but I am unsure how to proceed from here, as I keep getting errors.</p>
  
  <p>Thanks</p>