r - select first values after lead/lag (dplyr)
<p>I am trying to simply select the first two or three values of a <code>leaded</code> variable. </p>

<p>Imagine my data looks like this </p>

<pre><code>       id variable  leadvar
1       a        0     0
2       a        1     0
3       a        1     0
4       b        0     0
5       b        0     0
6       b        1     0
7       c        0     0
8       c        0     0
9       c        0     0
10      d        1     0
11      d        1     0
12      d        1     0
</code></pre>

<p>What I want is to first <code>lead</code> the <code>variable</code>, with the condition that <code>lead minus 1 = 0</code> (for each <code>id</code>) (which means that the lead variable should take <code>1</code> if a <code>1</code> is preceded by <code>0</code>), such as : </p>

<pre><code>       id variable  leadvar
1       a        0     1
2       a        1     0
3       a        1     0
4       b        0     0
5       b        0     1
6       b        1     0
7       c        0     0
8       c        0     0
9       c        0     0
10      d        1     0
11      d        1     0
12      d        1     0
</code></pre>

<p>and then select the first rows after the lead (as well as the lead variable itself), like this : </p>

<pre><code>       id variable  leadvar
        a        0     1
        a        1     0

        b        0     1
        b        1     0
</code></pre>

<p>I am struggling with the last step. I would like to be able to select freely the numbers of rows after the lead. How can I do this ?  </p>

<p>My code is :     </p>

<p>In order to compute the <code>lead</code> </p>

<pre><code>library(dplyr) 

dt = dt %&gt;% group_by(id) %&gt;% mutate(leadvar = ifelse(variable == 0 &amp; lead(variable == 1, default = 0), 1, 0) )
</code></pre>

<p>What I tried for selecting 2 rows after the lead, but it doesn't work </p>

<pre><code>dt %&gt;% group_by(id) %&gt;% mutate(V4 = variable + leadvar) %&gt;% mutate(m = 1:n()) %&gt;% filter(m &lt; 3)
</code></pre>

<p>The data </p>

<pre><code>dt = structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("a", "b", "c", "d"), class = "factor"), 
variable = c(0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1), lead = c(1, 
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0)), class = "data.frame", .Names = c("id", "variable", "lead"), row.names = c(NA, -12L))
</code></pre>