Streamline dplyr mutation of selected groups
<p><strong>A general question:</strong></p>

<p>Is there a way to use dplyr to identify groups of interest and mutate only those groups?</p>

<p><strong>An Instantiation of Said Question</strong></p>

<p>Imagine I have some values, which are labeled as being part of groups.</p>

<p>In some groups, the spread of the values is too great.</p>

<p>I want to make an adjustment to the lower values of those groups.</p>

<p>I can generate some synthetic data like so:</p>

<pre><code>groups &lt;- floor(runif(1000,1,100))
values &lt;- rnorm(1000,0,1)
df     &lt;- data.frame(group=groups,val=values)
</code></pre>

<p>I can identify groups of interest like so:</p>

<pre><code>groups_to_adjust &lt;- df %&gt;% group_by(group) %&gt;% summarise(diff=max(val)-min(val)) %&gt;% filter(diff&gt;4) %&gt;% select(group)
</code></pre>

<p>I can then adjust those groups like so:</p>

<pre><code>df &lt;- df %&gt;% mutate(val=ifelse(group %in% groups_to_adjust$group, ifelse(val&lt;0,val+4,val), val))
</code></pre>

<p>Ideally, all of this could be done in a single dplyr chain. Is there a clean way to achieve that? I imagine:</p>

<pre><code>df %&gt;% group_by(group) %&gt;% group_filter(max(val)-min(val)&gt;4) %&gt;% mutate(val=ifelse(val&lt;0,val+4,val)) %&gt;% ungroupfilter()
</code></pre>

<p>Or something similar.</p>