Command reference

duplicates — inspect, tag, and remove repeated records

Identify observations that share the same values in a chosen set of variables. Report duplicates before deciding whether repeated records are errors or valid observations.

Syntax

duplicates report [varlist] [if condition] [in first/last]
duplicates list [varlist] [, options]
duplicates examples [varlist] [, options]
duplicates tag [varlist], generate(newvar)
duplicates drop [varlist] [, force]

varlist defines what counts as a duplicate. With id, observations sharing an ID match even if other values differ. Without a variable list, all variables define the match. The subcommands also accept if and in to examine a subset.

Subcommands and display options

report
Show how many groups and observations are duplicated and how many observations are surplus. A group of three matching rows has three duplicate observations but only two surplus observations.
list
Display every observation belonging to a duplicate group. The added _dupcount column gives the number of observations in that group.
examples
Display one representative observation per duplicate group, rather than every matching observation.
tag, generate(newvar)
Create a variable holding the group size minus one: 0 for a unique observation, 1 on both observations of a pair, and so on. The target name must be new. Observations outside a selection get missing tags.
drop
Keep the first selected observation in each duplicate group and remove the later ones. The current row order determines which observation survives. In stats.camp, omitting the variable list requires force; an explicit key such as duplicates drop id does not.
noobs, nolabel, abbreviate(#)
For list or examples, omit observation numbers, show numeric codes instead of value labels, or shorten displayed variable names to the specified width. These options affect the display, not the dataset.
sepby(varlist)
For list or examples, order the displayed duplicate observations by these variables. The dataset’s row order is unchanged.

Example

The sample deliberately makes a second copy of students 1 and 2. It reports repeated IDs, tags and lists them, removes the surplus copies, and reports again.

clear
import delimited "data/student_scores.csv"
expand 2 if id <= 2
duplicates report id
duplicates tag id, generate(duplicate_count)
list id math duplicate_count if duplicate_count > 0
duplicates drop id
duplicates report id
Open example in browser

Sample data included. Opens in a new tab; click Run.

What to look for

After expansion, there are 26 observations. Two duplicate groups contain four observations in total, with two surplus observations. All four receive duplicate_count = 1. Dropping the surplus copies returns the dataset to 24 observations, and the final report finds no duplicated IDs.