title: How to lag the same column in dplyr?
body: <p>I am trying to mutate and lag the same column in R dplyr, per the reproducible code at the bottom of this post. That code doesn't give my what I'm looking for. What am I doing wrong?</p>
  <p>Running the code gives me these incorrect results, where column <code>nameCntMult</code> is the one I'm trying to lag:</p>
  <pre><code>&gt; dataFill
  # A tibble: 6 x 4
    Name   Code nameCnt nameCntMult
    &lt;chr&gt; &lt;dbl&gt;   &lt;int&gt;       &lt;dbl&gt;
  1 R         0       1           1
  2 R         0       2           2
  3 T         0       1           1
  4 R         0       3           3
  5 N         1       1          NA
  6 N         1       2           2
  </code></pre>
  <p>When I'm looking for these results, rendered in XLS:</p>
  <p><a href="https://i.stack.imgur.com/VuDwn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VuDwn.png" alt="enter image description here" /></a></p>
  <p>Reproducible code:</p>
  <pre><code>library(dplyr)
  
  data &lt;- 
    data.frame(
      Name = c(&quot;R&quot;,&quot;R&quot;,&quot;T&quot;,&quot;R&quot;,&quot;N&quot;,&quot;N&quot;),
      Code = c(0,0,0,0,1,1)
    )
  
  dataFill &lt;-data %&gt;%
    group_by(Name, Code) %&gt;%
      mutate(nameCnt = row_number())%&gt;%
      mutate(nameCntMult = nameCnt * 2) %&gt;%
      mutate(nameCntMult = ifelse(Code == 0, nameCnt, lag(nameCntMult))) %&gt;%
    ungroup()
  
  dataFill
  </code></pre>