title: How to efficiently identify duplicates and correctly recast a sequence of numbers in R?
body: <p>I'm working on looping code in R that identifies any disallowed duplications in a sequence of numbers, and then reiteratively recasts the numbers into a correct sequence. As shown in the image below starting with the first step in an assumed loop, where <code>dat</code> is the initial data frame whose sequences are to be checked, <code>uniqCodes</code> isolates the unique Codes from <code>dat</code>, and then <code>ckDupes</code> counts any disallowed duplicates in column <code>cntDupes1</code>, reassigns the next sequential Code in those instances of disallowed duplicates in column <code>reCode1</code>, and then another check for disallowed duplicates in column <code>cntDupes2</code>:</p>
  <p><a href="https://i.stack.imgur.com/hfrJd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hfrJd.png" alt="enter image description here" /></a></p>
  <p>Below is my code for these 3 data frames, that works in this scenario. Is there a more efficient way to do the duplication identification and resequencing currently done in <code>ckDupes</code>? This is the kind of tangled code that I won't understand a month from now and it needs to be clear and efficient since it'll be in an iterative process as I build out the loop.</p>
  <p>Code:</p>
  <pre><code>library(dplyr)
  
  dat &lt;- data.frame(Element= c(&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;R&quot;),
                    Code = c(1.1,2.1,2.2,2.2,3))
  
  uniqCodes &lt;- dat %&gt;% select(Code) %&gt;% distinct()
  
  ckDupes &lt;- dat %&gt;% 
    mutate(cntDupes1 = sapply(1:n(), function(x) sum(Element[1:x]==Element[x] &amp; Code[1:x] == Code[x]))-1) %&gt;%
    mutate(reCode1 = ifelse(cntDupes1 &gt; 0,uniqCodes[match(Code,uniqCodes$Code)+cntDupes1,],Code)) %&gt;%
    mutate(cntDupes2 = sapply(1:n(), function(x) sum(Element[1:x]==Element[x] &amp; reCode1[1:x] == reCode1[x]))-1)
  </code></pre>