title: R Check for levels within a group and duplicate row if not present
body: <p>I have a problem with in Shiny which I will show in a simple example:</p>
  
  <p>I have the following data:</p>
  
  <pre><code>Group&lt;-c("A","A","B","C","C","D")
  Value&lt;-c(1,2,6,7,3,9)
  
  df&lt;-data.frame(Group, Value)
  
    Group Value 
       A     1   
       A     2   
       B     6   
       C     7   
       C     3   
       D     9   
  </code></pre>
  
  <p>Then I add a row to see how many reps a group has:</p>
  
  <pre><code>df$num &lt;- ave(df$Value, df$Group,  FUN = seq_along)
  
    Group Value num
       A     1   1
       A     2   2
       B     6   1
       C     7   1
       C     3   2
       D     9   1
  </code></pre>
  
  <p>Now, I would like it, to check if the group contains a 2nd rep, and if not, duplicate the 1st row of the group (containing num=1) and setting num to 2.
  So I would like to end up with:</p>
  
  <pre><code>  Group Value num
       A     1   1
       A     2   2
       B     6   1
       B     6   2 #this row is added
       C     7   1
       C     3   2
       D     9   1
       D     9   2 #this row is added
  </code></pre>
  
  <p>I have tried to search for solution, but I mainly ended up with subject like a condition that is <a href="https://stackoverflow.com/questions/29424290/creating-duplicates-of-data-frame-rows-based-on-a-count-variable">based on a certain value</a>, rather than conditions within a group. </p>
  
  <p>Could someone help me? I would appreciate it a lot!</p>