title: R How to add rows based on another variable then transform from wide format to long format
body: <p>I would like to restructure my data frame in two steps.</p>
  <p>Original data set:</p>
  <pre><code>structure(list(ID = c(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;), Type = c(&quot;A&quot;, 
  &quot;B&quot;, &quot;B&quot;, &quot;A&quot;, &quot;A&quot;, &quot;C&quot;), A_Var1 = c(&quot;Yes&quot;, &quot;None&quot;, &quot;None&quot;, &quot;Yes&quot;, 
  &quot;None&quot;, &quot;None&quot;), A_Var2 = c(&quot;Yes&quot;, &quot;None&quot;, &quot;None&quot;, &quot;Yes&quot;, &quot;Yes&quot;, 
  &quot;None&quot;), A_Var3 = c(&quot;Yes&quot;, &quot;None&quot;, &quot;None&quot;, &quot;Yes&quot;, &quot;Yes&quot;, &quot;Yes&quot;
  ), B_Var1 = c(&quot;NA&quot;, &quot;None&quot;, &quot;None&quot;, &quot;NA&quot;, &quot;NA&quot;, &quot;None&quot;), B_Var2 = c(&quot;NA&quot;, 
  &quot;None&quot;, &quot;None&quot;, &quot;NA&quot;, &quot;NA&quot;, &quot;Yes&quot;), B_Var3 = c(&quot;NA&quot;, &quot;None&quot;, 
  &quot;None&quot;, &quot;NA&quot;, &quot;NA&quot;, &quot;Yes&quot;)), row.names = c(NA, -6L), class = c(&quot;tbl_df&quot;, 
  &quot;tbl&quot;, &quot;data.frame&quot;))
  </code></pre>
  <p>First, I am hoping to add new rows for each <em>ID</em> based on the sequential order of <em>Type</em>. There are 3 types in the data frame, and the order is A,B,C. For each <em>ID</em>, if I see type B, I would like to add a row with the same <em>ID</em> but type A above; if I see type C, then I will add two rows with same ID but type A and type B above.</p>
  <p>Second, I am hoping to transform the data frame after step 1 from a wide format to a long format. So I fill <em>Var1</em>, <em>Var2</em>, <em>Var3</em> to its corresponding type.</p>
  <p>Excepted data set:</p>
  <pre><code>structure(list(ID = c(&quot;1&quot;, &quot;2&quot;, &quot;2&quot;, &quot;3&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, 
  &quot;6&quot;, &quot;6&quot;), Type = c(&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;A&quot;, &quot;B&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, 
  &quot;C&quot;), Var1 = c(&quot;Yes&quot;, &quot;None&quot;, &quot;None&quot;, &quot;None&quot;, &quot;None&quot;, &quot;Yes&quot;, 
  &quot;None&quot;, &quot;None&quot;, &quot;None&quot;, NA), Var2 = c(&quot;Yes&quot;, &quot;None&quot;, &quot;None&quot;, 
  &quot;None&quot;, &quot;None&quot;, &quot;Yes&quot;, &quot;Yes&quot;, &quot;None&quot;, &quot;Yes&quot;, NA), Var3 = c(&quot;Yes&quot;, 
  &quot;None&quot;, &quot;None&quot;, &quot;None&quot;, &quot;None&quot;, &quot;Yes&quot;, &quot;Yes&quot;, &quot;Yes&quot;, &quot;Yes&quot;, NA
  )), row.names = c(NA, -10L), class = &quot;data.frame&quot;)
  </code></pre>
  <p>I have a hard time figuring out how to accomplish both steps in a nice order. Would appreciate any comment!</p>