<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/quickly-check-your-id-variables/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://edwinth.github.io/blog/unique_id/"> That’s so Random</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Virtually every dataset has them; id variables that link a record to a subject and/or time point. Often one column, or a combination of columns, forms the unique id of a record. For instance, the combination of patient_id and visit_id, or ip_adress and visit_time. The first step in most of my analyses is almost always checking the uniqueness of a variable, or a combination of variables. If it is not unique, may assumptions about the data may be wrong, or there are data quality issues. Since I do this so often, I decided to make a little wrapper around this procedure. The <code>unique_id</code> function will return <code>TRUE</code> if the evaluated variables indeed are the unique key to a record. If not, it will return all the records for which the id variable(s) are duplicated so we can pinpoint the problem right away. It uses <code>dplyr</code> v.0.7.1, so make sure that it is loaded.</p>
<div>
<pre><code><span>library</span><span>(</span><span>dplyr</span><span>)</span><span>
</span><span>some_df</span><span> </span><span>&lt;-</span><span> </span><span>data_frame</span><span>(</span><span>a</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>1</span><span>,</span><span> </span><span>2</span><span>,</span><span> </span><span>3</span><span>,</span><span> </span><span>3</span><span>,</span><span> </span><span>4</span><span>),</span><span> </span><span>b</span><span> </span><span>=</span><span> </span><span>101</span><span>:</span><span>105</span><span>,</span><span> </span><span>val</span><span> </span><span>=</span><span> </span><span>round</span><span>(</span><span>rnorm</span><span>(</span><span>5</span><span>),</span><span> </span><span>1</span><span>))</span><span>
</span><span>some_df</span><span> </span><span>%>%</span><span> </span><span>unique_id</span><span>(</span><span>a</span><span>)</span><span>
</span></code></pre>
</div>
<div>
<pre><code>## # A tibble: 2 x 3
##       a     b   val
##   </code></pre></div>