title: Adding dummy variable with multiple conditions
body: <p>I have a dataframe called &quot;insider_dataset&quot; composed as follows:</p>
  <pre><code>personid cusip6 acqdisp trandate   month  year
       &lt;dbl&gt; &lt;chr&gt;  &lt;chr&gt;   &lt;date&gt;     &lt;dbl&gt; &lt;dbl&gt;
  1 13080542 143436 D       2000-01-03     1  2000
  2 12260711 143436 A       2002-01-07     1  2002
  3 12700206 143436 D       2010-10-03    10  2010
  4     7161 382388 A       2011-09-03     9  2011
  5     7161 382388 A       2012-09-08     9  2012
  6     7161 382388 A       2013-09-03     9  2013
  </code></pre>
  <p>My aim is to add a dummy variable called &quot;routine_dummmy&quot; equal to 1 if the personid is appearing with the same acqdisp and the same month in the two years preceding trandate, and equal to zero otherwise. In the example the dummy variable would be equal to 1 only in row 6. What i tried is:</p>
  <pre><code>while (i &lt;= nrow(insider_dataset)) {
    if (nrow(subset(insider_dataset, personid == insider_dataset$personid[i]
                    &amp; month == month[i] &amp; year == year[i]-1 | year == year[i]-2 &amp; acqdisp == 
                    acqdisp[i])) &gt; 1) {
      insider_dataset$routine_dummy[i] &lt;- 1
    }
    else insider_dataset$routine_dummy[i] &lt;- 0
    i &lt;- i+1
  }
  </code></pre>
  <p>Which appears to work, but it is very slow in my very large datasets. Is there a more compact and efficient way of doing this?</p>