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 dat is the initial data frame whose sequences are to be checked, uniqCodes isolates the unique Codes from dat, and then ckDupes counts any disallowed duplicates in column cntDupes1, reassigns the next sequential Code in those instances of disallowed duplicates in column reCode1, and then another check for disallowed duplicates in column cntDupes2:
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 ckDupes? 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.
Code:
library(dplyr)
dat <- data.frame(Element= c("X","X","X","X","R"),
Code = c(1.1,2.1,2.2,2.2,3))
uniqCodes <- dat %>% select(Code) %>% distinct()
ckDupes <- dat %>%
mutate(cntDupes1 = sapply(1:n(), function(x) sum(Element[1:x]==Element[x] & Code[1:x] == Code[x]))-1) %>%
mutate(reCode1 = ifelse(cntDupes1 > 0,uniqCodes[match(Code,uniqCodes$Code)+cntDupes1,],Code)) %>%
mutate(cntDupes2 = sapply(1:n(), function(x) sum(Element[1:x]==Element[x] & reCode1[1:x] == reCode1[x]))-1)
