When to use "Do" function in dplyr : <p>I've learned that <code>Do</code> function is used when you want to apply a function to each group.</p>

<p>for example, if I want to pull top 2 rows from "A", "C", and "I" categories of variable <code>Index</code>, following syntax can be used.</p>

<pre><code>t &lt;- mydata %&gt;% filter(Index %in% c("A", "C", "I")) %&gt;% group_by(Index) %&gt;% do(head(.,2))
</code></pre>

<p>I understand that after grouping by index, <code>do</code> function is used to compute head(.,2) for each group.</p>

<p>However, on some occasions, <code>do</code> is not used at all. For example, To compute mean of variable <code>Y2014</code> grouped by variable <code>Index</code>, I thought that following code should be used.</p>

<pre><code>t &lt;- mydata %&gt;% group_by(Index) %&gt;% do(summarise(Mean_2014 = mean(Y2014)))
</code></pre>

<p>however, above syntax returns error</p>

<pre><code>Error in mean(Y2014) : object 'Y2014' not found
</code></pre>

<p>But if I remove <code>do</code> from the syntax, it returns what I exactly wanted.</p>

<pre><code>t &lt;- mydata %&gt;% group_by(Index) %&gt;% summarise(Mean_2014 = mean(Y2014))
</code></pre>

<p>I'm really confused about usage of <code>do</code> function in dplyr. It seems inconsistent to me. When should I use and not use <code>do</code> function? Why should I use <code>do</code> in the first case and not in the second case?</p>
