I have a vector of path steps and there's one particular path step that if it repeats I want to eliminate the repetitions.
For example,
my_vec = "A > A > X > B > X > X > X > C > C"
Now if 'X' repeats, then I want to eliminate all repetitions of X besides the first one, while preserving the order of the rest of the elements, such that my desired outcome is:
my_vec = "A > A > X > B > X > C > C", where the repetitive X's are eliminated from the middle.
I tried this with a for-loop and if-else combination, such that I would detect if a previous element in the vector also contains 'X', then replace the element with NA and afterwards I could remove the NA items, but this approach does not provide the desired outcome.
I tried looking here and here, but these just filter out the unique elements, while I want to perform this action on a particular element.
Here's my code:
my_vec <- unlist(str_split(my_vec, '>') )
for (i in length(my_vec)){
if (grepl('X', my_vec[i]) & grepl('X', my_vec[i-1])) {
steps[i] <- NA
} else {
next()
}}
my_new_vec <- str_c(steps, collapse = '>')
However, the output is exactly the same as input and nothing is changed into NA.