Use rle to group by runs when using dplyr : <p>In R, I want to summarize my data after grouping it based on the runs of a variable <code>x</code> (aka each group of the data corresponds to a subset of the data where consecutive <code>x</code> values are the same). For instance, consider the following data frame, where I want to compute the average <code>y</code> value within each run of <code>x</code>:</p>

<pre><code>(dat &lt;- data.frame(x=c(1, 1, 1, 2, 2, 1, 2), y=1:7))
#   x y
# 1 1 1
# 2 1 2
# 3 1 3
# 4 2 4
# 5 2 5
# 6 1 6
# 7 2 7
</code></pre>

<p>In this example, the <code>x</code> variable has runs of length 3, then 2, then 1, and finally 1, taking values 1, 2, 1, and 2 in those four runs. The corresponding means of <code>y</code> in those groups are 2, 4.5, 6, and 7.</p>

<p>It is easy to carry out this grouped operation in base R using <code>tapply</code>, passing <code>dat$y</code> as the data, using <code>rle</code> to compute the run number from <code>dat$x</code>, and passing the desired summary function:</p>

<pre><code>tapply(dat$y, with(rle(dat$x), rep(seq_along(lengths), lengths)), mean)
#   1   2   3   4 
# 2.0 4.5 6.0 7.0 
</code></pre>

<p>I figured I would be able to pretty directly carry over this logic to dplyr, but my attempts so far have all ended in errors:</p>

<pre><code>library(dplyr)
# First attempt
dat %&gt;%
  group_by(with(rle(x), rep(seq_along(lengths), lengths))) %&gt;%
  summarize(mean(y))
# Error: cannot coerce type 'closure' to vector of type 'integer'

# Attempt 2 -- maybe "with" is the problem?
dat %&gt;%
  group_by(rep(seq_along(rle(x)$lengths), rle(x)$lengths)) %&gt;%
  summarize(mean(y))
# Error: invalid subscript type 'closure'
</code></pre>

<p>For completeness, I could reimplement the <code>rle</code> run id myself using <code>cumsum</code>, <code>head</code>, and <code>tail</code> to get around this, but it makes the grouping code tougher to read and involves a bit of reinventing the wheel:</p>

<pre><code>dat %&gt;%
  group_by(run=cumsum(c(1, head(x, -1) != tail(x, -1)))) %&gt;%
  summarize(mean(y))
#     run mean(y)
#   (dbl)   (dbl)
# 1     1     2.0
# 2     2     4.5
# 3     3     6.0
# 4     4     7.0
</code></pre>

<p>What is causing my <code>rle</code>-based grouping code to fail in <code>dplyr</code>, and is there any solution that enables me to keep using <code>rle</code> when grouping by run id?</p>
