title: Using Variable in lag function of dplyr - R
body: <p>I have written a function with variables. I am trying to compute lag for a given column of a dataframe. I am unable to do so. Following is my code snippet:</p>
  
  <pre><code>calculateLag &lt;- function(df,lagCol,lagInterval){
  
    df &lt;- df %&gt;%
     group_by(grp = cumsum(c(TRUE, diff(t)!=1))) %&gt;%
  
     mutate(val_lag = lag(df[,lagCol],lagInterval)) %&gt;%
     ungroup() %&gt;%
     select(-grp)
  
     return(df)
  }
  </code></pre>
  
  <p>I am getting error as : </p>
  
  <pre><code> Error in `[.data.table`(df, , lagCol) : 
   j (the 2nd argument inside [...]) is a single symbol but column name 'lagCol' is not found. Perhaps you intended DT[,..lagCol] or DT[,lagCol,with=FALSE]. This difference to data.frame is deliberate and explained in FAQ 1.1.    
  </code></pre>
  
  <p>Expected Result:</p>
  
  <pre><code>                   t         val   val_lag   val_lag2
   2005-01-17 17:30:00       14.3        NA         NA
   2005-01-17 18:30:00       14.0      14.3         NA
   2005-01-17 19:30:00       14.3      14.0       14.3
   2005-01-17 22:30:00       14.9        NA         NA
   2005-01-17 23:30:00       14.2      14.9         NA
   2005-01-18 00:30:00       14.1      14.2       14.9
  </code></pre>
  
  <p>Can someone help me in this?</p>
  
  <p>Thanks</p>