Command reference

merge — join datasets by identifying variables

Combine the dataset in memory with another file by matching one or more key variables. Merge can add information such as school characteristics to student records while recording which observations matched.

Syntax

merge 1:1 keyvars using "filename.csv" [, options]
merge m:1 keyvars using "filename.csv" [, options]
merge 1:m keyvars using "filename.csv" [, options]

The dataset in memory is the master; the file after using is the using dataset. Both must contain keyvars. The relation describes whether each key can appear once or many times on each side. By default, unmatched observations from both datasets are retained.

Matching relations and options

1:1, m:1, 1:m
1:1 requires unique keys in both datasets. m:1 permits repeated keys in the master but requires uniqueness in the using dataset; it is suitable for adding school information to many students. 1:m reverses that requirement. Violating the declared uniqueness causes an error.
keepusing(varlist)
Bring in only these non-key variables from the using file. The key variables are kept automatically. Use it when the second dataset contains many columns you do not need.
generate(newvar)
Choose the name of the match-status variable; its default name is _merge. Code 1 means master only, 2 means using only, and 3 means matched.
nogen
Do not create a match-status variable. This cannot be combined with generate(). Keeping the indicator is useful while checking a merge.
keep(master using match)
Retain only the named result categories. For example, keep(master match) keeps every master observation and excludes using-only rows. Numeric codes 1, 2, and 3 are also accepted.
assert(master using match)
Require every result to belong to the listed categories. assert(match) fails if any observation is unmatched. This check runs before keep() filters the result, so unexpected categories cannot be hidden by filtering.

Example

The sample joins student scores to school information by student ID. It tabulates the match indicator and lists the IDs that occur in only one file.

clear
import delimited "data/student_scores.csv"
merge 1:1 id using "data/student_schools.csv"
tabulate _merge
list id math school _merge if _merge != 3
Open example in browser

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

What to look for

There are 22 matched students, two master-only students (IDs 23 and 24), and one using-only student (ID 25). The unmatched students remain in the result: school information is missing for IDs 23 and 24, and test scores are missing for ID 25. These are merge outcomes to inspect, not automatically records to delete.