 <p>A solution with the <code>data.table</code> package:</p> <pre><code>require(data.table) df &lt;- data.table(CLNCL_TRIAL_ID = c(89794, 89794,8613, 8613), SITE_ID = c(12456, 12456, 100341, 30807)) df[,length(unique(SITE_ID)),by=CLNCL_TRIAL_ID] </code></pre> <p>Produces</p> <pre><code> CLNCL_TRIAL_ID V1 1: 89794 1 2: 8613 2 </code></pre>