Identify duplicate together with original observation in R (maybe by clustering)
<p>I have the suspicion that respondents are cheating. I have found duplicate answers, but if I only use the duplicated() and/or unique() function, I only get either the duplicates (without origin) or the unique values (without the duplicates). I want to know which one are duplicates from which observations. Is there a function in R with which I can easily find which observations have the same answer pattern?</p>

<pre><code>#df
id &lt;- c("l","l","l","p","p","a","a","a")
show &lt;- c("broadway","cats","alladin","broadway","cats","broadway","cats","alladin")
v1 &lt;- c(1,2,2,1,3,1,2,1)
v2 &lt;- c(1,2,2,2,4,1,2,3)
v3 &lt;- c(1,2,2,5,1,1,2,4)
df &lt;- data.frame(id,show,v1,v2,v3); df
</code></pre>

<p>Here's the script I've used to identify the duplicates. I am only interested in duplicates occurring in the numerical part of the dataframe, hence I only select columns 3 to 5.</p>

<pre><code>#script I'm using to find duplicates
duplicates &lt;- data.frame(which(duplicated(df[,3:5]))) 
</code></pre>

<p>This question is not a duplicate of <a href="https://stackoverflow.com/questions/16265808/identify-duplicates-and-mark-first-occurrence-and-all-others">Identify duplicates and mark first occurrence and all others</a>, because I am not interested in a binary output. A solution that would be of great help to me is if I could identify which clusters of duplicates exist. In this case, df[6,] is a duplicate of df[1,] (cluster 1) and df[3,] and df[7,] are duplicates of df[2,] (cluster 2)</p>

<p>Using Wietze's solution with the dplyr package led to a good solution:</p>

<pre><code> library(dplyr) 
 df %&gt;% group_by(v1, v2, v3) %&gt;% filter(n() &gt; 1)
</code></pre>

<p>Since I am not really familiar with the grammar that is used in dplyr, I have one more question. It looks like a column (n) is added at the end of the dataframe, but if I save the function as an object and ask for the final column, it doesn't return to me the n. How can I, using this solution, find my way back to my original dataframe with the n column added? This is how my desired output would look like using the dplyr package:</p>

<pre><code>id_e &lt;- c("l","l","l","a","a")
show_e &lt;- c("broadway","cats","alladin","broadway","cats")
v1_e &lt;- c(1,2,2,1,2)
v2_e &lt;- c(1,2,2,1,2)
v3_e &lt;- c(1,2,2,1,2)
dup_cluster &lt;- c(2,3,3,2,3)
df_expected &lt;- data.frame(id_e,show_e,v1_e,v2_e,v3_e,dup_cluster); df_expected
</code></pre>

<p>I post here the two solutions that worked for me. Solution 1:</p>

<pre><code> df %&gt;% group_by(v1, v2, v3) %&gt;% mutate(n = n()) %&gt;% filter(n &gt; 1) #add an extra column with a new category
 df &lt;- dataframe(df) #transform back into dataframe
</code></pre>

<p>Solution 2:</p>

<pre><code>setDT(df)[, .(.N, id, show) , by=.(v1,v2,v3)][N&gt;1,]
</code></pre>