title: R: add new variable based on value change using dplyr
body: <p>I have  dataset like the following:</p>
  <pre><code>id &lt;- c(1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2)
  v1 &lt;- c(&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;)  
  v2 &lt;- c(1,1,1,2,2,2,2,2,2,2,3,3,3,1,1,1,2,2,2,2,2,2,2,3,3,3)
  mydata&lt;- data.frame(id,v1,v2)
  </code></pre>
  <p>v1 represents moving or not from a condition A= Moving, B= Not moving and v2 is a sequence from locations every id passess from, 1-&gt;2-&gt;3. I want to add a column that says whether: id moving from 1 to 2, id remains at 2, id moving from 2 to 3.</p>
  <p>Specifically, I try to add a column to the data frame based on the following conditions: if v1=A (id moving) and v2=1 or (v2=2 if previously v2 had been 1) phase= &quot;Going&quot;, if v1=B (not moving) phase &quot;Staying&quot; and if v1=A (moving) and v2=3 or (v2=2 following a &quot;Staying&quot; phase) phase = &quot;Returning&quot;.</p>
  <p>Specifically, my intended output is:</p>
  <pre><code>phase &lt;- c(&quot;Going&quot;,&quot;Going&quot;,&quot;Going&quot;,&quot;Going&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Returning&quot;,&quot;Returning&quot;,&quot;Returning&quot;,&quot;Returning&quot;,&quot;Going&quot;,&quot;Going&quot;,&quot;Going&quot;,&quot;Going&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Staying&quot;,&quot;Returning&quot;,&quot;Returning&quot;,&quot;Returning&quot;,&quot;Returning&quot;)
  
  mydata2 &lt;- cbind(mydata, phase)
  </code></pre>
  <p>I tried the following:</p>
  <pre><code>mydata &lt;-mydata %&gt;% group_by(id)%&gt;% mutate(phase= case_when(v1 == &quot;A&quot; &amp; (v2 == 1 | v2==2) ~ &quot;Going&quot;, phase == &quot;A&quot; &amp; (v2 == 2 | v2==3) ~ &quot;Returning&quot;, phase == &quot;B&quot; ~ &quot;Staying&quot;))
  </code></pre>
  <p>But <code>(v2 == 1 | v2==2)</code> doesn't account for the order of the values. Any ideas? Apologies if it sounds complicated happy to clarify further.</p>