title: Major dplyr functions in a function
body: <p>I have seen a couple of posts of how to write one's own function with <code>dplyr</code> functions. For example, you can see how you can use <code>group_by (regroup)</code> and <code>summarise</code> in <a href="https://stackoverflow.com/questions/21815060/dplyr-how-to-use-group-by-inside-a-function">this post</a>. I thought that it would be interesting to see if I can write a function using major <code>dplyr</code> functions. My hope is that we can further understand how to write functions using <code>dplyr</code> functions.</p>
  
  <p><strong>DATA</strong></p>
  
  <pre><code>country &lt;- rep(c("UK", "France"), each = 5)
  id &lt;- rep(letters[1:5], times = 2)
  value &lt;- runif(10, 50, 100)
  foo &lt;- data.frame(country, id, value, stringsAsFactors = FALSE)
  </code></pre>
  
  <p><strong>GOAL</strong></p>
  
  <p>I wanted to write the following process in a function.</p>
  
  <pre><code>foo %&gt;%
      mutate(new = ifelse(value &gt; 60, 1, 0)) %&gt;%
      filter(id %in% c("a", "b", "d")) %&gt;%
      group_by(country) %&gt;%
      summarize(whatever = sum(value))
  </code></pre>
  
  <p><strong>TRY</strong></p>
  
  <pre><code>### Here is a function which does the same process
  
  myFun &lt;- function(x, ana, bob, cathy) x %&gt;%
      mutate(new = ifelse(ana &gt; 60, 1, 0)) %&gt;%
      filter(bob %in% c("a", "b", "d")) %&gt;%
      regroup(as.list(cathy)) %&gt;%
      summarize(whatever = sum(ana))
  
  myFun(foo, value, id, "country")
  
  Source: local data frame [2 x 2]
  
    country whatever
  1  France 233.1384
  2      UK 245.5400
  </code></pre>
  
  <p>You may realise that <code>arrange()</code> is not there. This is the one I am struggling. Here are two observations. The first experiment was successful. The order of the countries changed from UK-France to France-UK. But the second experiment was not successful.</p>
  
  <pre><code>### Experiment 1: This works for arrange()
  
  myFun &lt;- function(x, ana) x %&gt;%
           arrange(ana)
  
  myFun(foo, country)
  
     country id    value
  1   France  a 90.12723
  2   France  b 86.64229
  3   France  c 74.93320
  4   France  d 80.69495
  5   France  e 72.60077
  6       UK  a 84.28033
  7       UK  b 67.01209
  8       UK  c 94.24756
  9       UK  d 79.49848
  10      UK  e 63.51265
  
  
  ### Experiment2: This was not successful.
  
  myFun &lt;- function(x, ana, bob) x %&gt;%
           filter(ana %in% c("a", "b", "d")) %&gt;%
           arrange(bob)
  
  myFun(foo, id, country)
  
  Error: incorrect size (10), expecting :6
  
  ### This works, by the way.
  foo %&gt;%
  filter(id %in% c("a", "b", "d")) %&gt;%
  arrange(country)
  </code></pre>
  
  <p>Given the first experiment was successful, I have a hard time to understand why the second experiment failed. There may be something one has to do in the 2nd experimentDoes anybody have an idea? Thank you for taking your time.</p>