title: dplyr: comparing values within a variable dependent on another variable
body: <p>How can I compare values within a variable dependent on another variable with dplyr?</p>
  
  <p>The df is based on choice data (long format) from a survey. It has one variable that indicates a participants <em>id</em>, another that indicates the choice <em>inst</em>ance and one that indicates which <em>alt</em>ernative was chosen. 
  In my data I have the feeling that a lot of people tend to get bored of the task and therefore stick to one alternative for every instance. I would therefore like to identify people who always selected the same option from a certain instance onwards till the end.</p>
  
  <p>Here is an example df:</p>
  
  <pre><code>set.seed(0)
  df &lt;- tibble(
      id = rep(1:5,each=12),
      inst = rep(1:12,5),
      alt = sample(1:3, size =60, replace=T),
  )
  </code></pre>
  
  <p>That looks like the following:</p>
  
  <pre><code>   id     inst alt
  1   1        1   3
  2   1        2   1
  3   1        3   2
  4   1        4   2
  5   1        5   3
  6   1        6   1
  7   1        7   3
  8   1        8   3
  9   1        9   2
  10  1       10   2
  11  1       11   1   &lt;-
  12  1       12   1   &lt;-
  13  2        1   1
  14  2        2   3
  ...
  </code></pre>
  
  <p>I would like to create two new variables <em>count</em> and <em>count_alt</em>. The new variable <em>count</em> should indicate how often the same value appeared in <em>alt</em> based on <em>id</em> and <em>inst</em>, only counting values from the end of <em>id</em>. So for participant (id==1) the <em>count</em> variable should be 2, since alternative 1 was chosen in the last two instances (11 &amp; 12). <em>The count_alt</em> would take the value 1 (always the same as inst == 12)</p>
  
  <p>The new df schould look like the following</p>
  
  <pre><code> id     inst   alt   count   count_alt
  1   1        1   3       2           1
  2   1        2   1       2           1
  3   1        3   2       2           1
  4   1        4   2       2           1
  5   1        5   3       2           1
  6   1        6   1       2           1
  7   1        7   3       2           1
  8   1        8   3       2           1
  9   1        9   2       2           1
  10  1       10   2       2           1
  11  1       11   1       2           1
  12  1       12   1       2           1     
  ...
  </code></pre>
  
  <p>I would prefer to solve this with dplyr and not with a loop since I want to incooperate it into further data wrangling steps. </p>