title: How to calculate recency in R
body: <p>I have the following data: </p>
  
  <pre><code>set.seed(20)
  round&lt;-rep(1:10,2)
  part&lt;-rep(1:2, c(10,10))
  game&lt;-rep(rep(1:2,c(5,5)),2)
  pay1&lt;-sample(1:10,20,replace=TRUE)
  pay2&lt;-sample(1:10,20,replace=TRUE)
  pay3&lt;-sample(1:10,20,replace=TRUE)
  decs&lt;-sample(1:3,20,replace=TRUE)
  previous_max&lt;-c(0,1,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,1,1,0)
  gamematrix&lt;-cbind(part,game,round,pay1,pay2,pay3,decs,previous_max )
  gamematrix&lt;-data.frame(gamematrix)
  </code></pre>
  
  <p>Here is the output:</p>
  
  <pre><code>       part game round pay1 pay2 pay3 decs previous_max
  1        1    1     1    9    5    6    2            0
  2        1    1     2    8    1    1    1            1
  3        1    1     3    3    5    5    3            0
  4        1    1     4    6    1    5    1            0
  5        1    1     5   10    3    8    3            0
  6        1    2     6   10    1    5    1            0
  7        1    2     7    1   10    7    3            0
  8        1    2     8    1   10    8    2            1
  9        1    2     9    4    1    5    1            0
  10       1    2    10    4    7    7    2            0
  11       2    1     1    8    4    1    1            0
  12       2    1     2    8    5    5    2            0
  13       2    1     3    1    9    3    1            1
  14       2    1     4    8    2   10    2            1
  15       2    1     5    2    6    2    3            1
  16       2    2     6    5    5    6    2            0
  17       2    2     7    4    5    1    2            0
  18       2    2     8    2   10    5    2            1
  19       2    2     9    3    7    3    2            1
  20       2    2    10    9    3    1    1            0
  </code></pre>
  
  <p>How can I calculate a new indicator variable "previous_max",which returns  whether in the next round of the same game, the same participant choose the <strong>maximal payoff</strong> from the <em>previous</em> round. 
  So I want something like follows: </p>
  
  <p>Participant (part) 1: </p>
  
  <p>In the first round of each game, previous_max is "0" (no previous round), in round 2, previous_max ="1", because in round 1, the maximal pay was max(pay1,pay2,pay3)=max(9,5,6)=9, and in round 2, the participant's decisions (decs) was 1 (which was the maximal value in previous round).  </p>
  
  <p>In round 3, previous_max=0, because the maximal value in round 2 was 8 (which is "pay1"), but the participant choose "3" (which is pay3). </p>