Recognize a given pattern in a vector and add the lacking elements to get the repitition of the given pattern

Viewed 49

This question is related to this Wide a dataframe and insert missing columns

Suppose we have a given pattern of 5 elements in this order: "A", "B", "C", "D", "E"

This pattern is repeated say 10 times. But sometimes some elements are lacking (see picture my vector (orange).

Is it possible in R to recognize the repeated pattern and fill in the lacking elements (see picture my desired output).

My vector:

my.vector <- c("A", "B", "C", "D", "E", "A", "B", "C", "D", "E", "B", "C", 
               "D", "E", "B", "C", "D", "E", "B", "C", "D", "E", "B", "C", "D", 
               "E", "B", "C", "D", "E", "B", "C", "D", "E", "A", "B", "C", "D", 
               "E", "B")

my.vector
 [1] "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "B" "C" "D" "E" "B" "C" "D" "E" "B" "C" "D" "E" "B" "C" "D" "E" "B" "C" "D" "E" "B" "C" "D" "E" "A" "B" "C" "D" "E" "B"

A graphical explanation:

Given pattern: enter image description here

My vector: enter image description here

My desired output: Red marked elements to be added enter image description here

1 Answers

Create a grouping column based on the diff of matching index with LETTERS[1:5], split (or use any grouping functions like tapply etc), and create a union with the 'LETTERS[1:5], unlistthelistandunname`

unname( unlist(lapply(split(my.vector, cumsum(c(TRUE, 
     diff(match(my.vector, LETTERS[1:5])) != 1))),
       function(x) union(LETTERS[1:5], x))))

-output

[1] "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A"
[37] "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E"

Or another option is complete

library(dplyr)
library(tidyr)
library(data.table)
tibble(col1 = my.vector) %>%
    group_by(rn = rowid(col1)) %>%
    complete(col1 = LETTERS[1:5]) %>%
    ungroup %>%
    pull(col1)

-output

1] "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E" "A"
[37] "B" "C" "D" "E" "A" "B" "C" "D" "E" "A" "B" "C" "D" "E"
Related