title: Variables as default arguments of a function, using dplyr
body: <h3>Goal</h3>
  
  <p>My goal is to define some functions for use within <code>dplyr</code> verbs, that use pre-defined variables. This is because I have some of these functions that take a bunch of arguments, of which many always are the same variable names.</p>
  
  <p>My understanding: This is difficult (and perhaps impossible) because <code>dplyr</code> will lazily evaluate user-specified variables later on, but any default arguments are not in the function call and therefore invisible to <code>dplyr</code>.</p>
  
  <h3>Toy example</h3>
  
  <p>Consider the following example, where I use <code>dplyr</code> to calculate whether a variable has changed or not (rather meaningless in this case):</p>
  
  <pre><code>library(dplyr)
  mtcars  %&gt;%
    mutate(cyl_change = cyl != lag(cyl))
  </code></pre>
  
  <p>Now, <code>lag</code> also supports alternate ordering like so:</p>
  
  <pre><code>mtcars  %&gt;%
    mutate(cyl_change = cyl != lag(cyl, order_by = gear))
  </code></pre>
  
  <p>But what if I'd like to create my own version of <code>lag</code> that always orders by <code>gear</code>? </p>
  
  <h3>Failed attempts</h3>
  
  <p>The naive approach is this:</p>
  
  <pre><code>lag2 &lt;- function(x, n = 1L, order_by = gear) lag(x, n = n, order_by = order_by)
  
  mtcars %&gt;%
    mutate(cyl_change = cyl != lag2(cyl))
  </code></pre>
  
  <p>But this obviously raises the error:</p>
  
  <blockquote>
    <p>no object named ‘gear’ was found</p>
  </blockquote>
  
  <p>More realistic options would be these, but they also don't work:</p>
  
  <pre><code>lag2 &lt;- function(x, n = 1L) lag(x, n = n, order_by = ~gear)
  lag2 &lt;- function(x, n = 1L) lag(x, n = n, order_by = get(gear))
  lag2 &lt;- function(x, n = 1L) lag(x, n = n, order_by = getAnywhere(gear))
  lag2 &lt;- function(x, n = 1L) lag(x, n = n, order_by = lazyeval::lazy(gear))
  </code></pre>
  
  <h3>Question</h3>
  
  <p>Is there a way to get <code>lag2</code> to correctly find <code>gear</code> within the data.frame that <code>dplyr</code> is operating on?</p>
  
  <ul>
  <li>One should be able to call <code>lag2</code> without having to provide <code>gear</code>.</li>
  <li>One should be able to use <code>lag2</code> on datasets that are not called <code>mtcars</code> (but do have <code>gear</code> as one it's variables).</li>
  <li>Preferably <code>gear</code> would be a default argument to the function, so it can still be changed if required, but this is not crucial.</li>
  </ul>