title: Advanced if/then/loop function to create new columns
body: <p>I am learning R (focused on the <strong>tidyverse</strong> packages) and am hoping that someone could help with the following problem that has me stumped.</p>
  
  <p>I have a data-set that looks similar to the following:</p>
  
  <pre><code>library("tibble")
  myData &lt;- frame_data(
    ~id, ~r1, ~r2, ~r3, ~r4, ~r5, ~r6, ~r7, ~r8, ~r9, ~r10, ~r11, ~r12, ~r13, ~r14, ~r15, ~r16,
    "A", 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    "B", 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    "C", 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2,
    "D", 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2,
    "E", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  )
  </code></pre>
  
  <p>Basically, I have multiple rows of respondent data, and each respondent gave 16 responses of either "1" or "2". </p>
  
  <p>For each respondent (i.e., each row) I would like to create an additional three columns:</p>
  
  <p>The first new column - called "switchCount" - identifies the number of times the respondent switched from a "2" response to a "1" response.</p>
  
  <p>The second new column - called "switch1" - identifies the index of the <em>first</em> time the respondent switched from a "2" response to a "1" response. </p>
  
  <p>The third new column - called "switch2" - identifies the index of the <em>final</em> time the respondent switched from a "2" response to a "1" response.</p>
  
  <p>If there is no switch and all values are "2", then return the index of 0.</p>
  
  <p>If there is no switch and all values are "1", then return the index of 16.</p>
  
  <p>The final datatable should therefore look like this:</p>
  
  <pre><code>myData &lt;- frame_data(
    ~id, ~r1, ~r2, ~r3, ~r4, ~r5, ~r6, ~r7, ~r8, ~r9, ~r10, ~r11, ~r12, ~r13, ~r14, ~r15, ~r16, ~switchCount, ~switch1, ~switch2,
    "A", 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1,
    "B", 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4,
    "C", 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 3, 9,
    "D", 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 3, 6, 15,
    "E", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 16, 16
  )
  </code></pre>