title: Apply function within mutate
body: <p>I have a data.table object which contains Time-stamps (measured as Seconds after Midnight). My aim is to run a function which returns for each row the number of observations which occurred at max $k$ seconds before the observation. </p>
  
  <pre><code>require(data.table, dplyr, dtplyr)
  set.seed(123)
  DF  &lt;- data.frame(Secs=cumsum(rexp(10000,1)))
  setDT(DF)  
  &gt; DF
                 Secs
  1: 8.434573e-01
  2: 1.420068e+00
  3: 2.749122e+00
  4: 2.780700e+00
  5: 2.836911e+00
  ---             
   9996: 1.003014e+04
   9997: 1.003382e+04
   9998: 1.003384e+04
   9999: 1.003414e+04
  10000: 1.003781e+04
  </code></pre>
  
  <p>The function I want to apply to each row is </p>
  
  <pre><code>nS&lt;-function(Second,k=5) 
      max(1,nrow(DF%&gt;%filter(Secs&lt;Second &amp; Secs&gt;=Second-k)))
  </code></pre>
  
  <p>One way to obtain what I want is to use apply, which takes rather long.</p>
  
  <pre><code> system.time(val &lt;- apply(DF,1,nS))
     User      System verstrichen 
    20.56        0.03       20.66 
  
  #Not working 
  DF%&gt;%mutate(nS=nS(Secs,100))%&gt;%head()
  
  # Also not working
  library(lazyeval)
  f = function(col1, new_col_name) {
      mutate_call = lazyeval::interp(~ nS(a), a = as.name(col1))
      DF%&gt;%mutate_(.dots=setNames(list(mutate_call),new_col_name))
  }
  head(f('Secs', 'nS'))
  
  DF%&gt;%mutate(minTime=Secs-k)%&gt;%head()
  </code></pre>
  
  <p>Isn't it possible to do this approach by using mutate?
  Thanks a lot for your help!</p>