title: Why does this dplyr group function give strange results?
body: <p>When I run the below reproducible code I get the desired grouping results in the <code>GroupRank</code> column shown immediately beneath:</p>
  <pre><code>library(dplyr)
  
  myData &lt;- 
    data.frame(
      Element = c(&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;A&quot;,&quot;C&quot;,&quot;C&quot;),
      Group = c(0,0,0,0,1,1)
    )
  
  myDataGroups &lt;- myData %&gt;%
    mutate(origOrder = row_number()) %&gt;%  
    group_by(Element) %&gt;% 
    mutate(ElementCnt = row_number()) %&gt;%
    ungroup() %&gt;%  
    mutate(Group = factor(Group, unique(Group))) %&gt;% 
    arrange(Group) %&gt;% 
    mutate(groupCt = cumsum(Group != lag(Group, 1, Group[[1]])) - 1L) %&gt;%  
    group_by(Group) %&gt;%  
    mutate(GroupRank = ElementCnt - max(0L,groupCt),
           GroupRank = if_else(as.character(Group) == &quot;0&quot;, ElementCnt, min(GroupRank))
    )%&gt;%  
    ungroup() %&gt;%
    arrange(origOrder)
  myDataGroups
  
  &gt; myDataGroups
  # A tibble: 6 x 6
    Element Group origOrder ElementCnt groupCt GroupRank
    &lt;chr&gt;   &lt;fct&gt;     &lt;int&gt;      &lt;int&gt;   &lt;int&gt;     &lt;int&gt;
  1 A       0             1          1      -1         1
  2 A       0             2          2      -1         2
  3 B       0             3          1      -1         1
  4 A       0             4          3      -1         3
  5 C       1             5          1       0         1
  6 C       1             6          2       0         1
  </code></pre>
  <p>However when I take the line from the above code <code>GroupRank = if_else(as.character(Group) == &quot;0&quot;, ElementCnt, min(GroupRank))</code> and simply add a max function like this <code>GroupRank = max(1L,if_else( as.character(Group) == &quot;0&quot;, ElementCnt, min(GroupRank)))</code>  (run as 1 and 1L both ways and get the same results) I get the strange output shown below. <code>GroupRank</code> shouldn´t have changed from the above output:</p>
  <pre><code>  Element Group origOrder ElementCnt groupCt GroupRank
    &lt;chr&gt;   &lt;fct&gt;     &lt;int&gt;      &lt;int&gt;   &lt;int&gt;     &lt;int&gt;
  1 A       0             1          1      -1         3
  2 A       0             2          2      -1         3
  3 B       0             3          1      -1         3
  4 A       0             4          3      -1         3
  5 C       1             5          1       0         1
  6 C       1             6          2       0         1
  </code></pre>
  <p>What am I doing wrong here? Am I using <code>max()</code> incorrectly?</p>