Indiana University
University Information Technology Services
  
What are archived documents?
Login>>
Login

Login is for authorized groups (e.g., UITS, OVPIT, and TCC) that need access to specialized Knowledge Base documents. Otherwise, simply use the Knowledge Base without logging in.

Close

In Stata, how do I merge two data sets in the many-to-one relationship?

Note: The .merge command supports 1:1, 1:m, m:1, and m:m match merges. For 1:1, see In Stata, how do I merge two data sets?

To merge two data sets, A.dta and B.dta (see below), which share the same key variable, id :

Data set A.dta :

+---------+ | id y | |---------| | 1 85 | | 1 47 | | 2 95 | | 4 36 | | 5 83 | +---------+

Data set B.dta :

+---------+ | id x | |---------| | 1 53 | | 2 23 | | 3 45 | +---------+

Stata 11

Sort by key variable(s) first, and then enter the merge command, making sure the data set with the "many" observations is the current data set in memory (for m:1 merges). An example using the above data sets follows:

use "C:\temp\B.dta", clear sort id save "C:\temp\B.dta", replace use "C:\temp\A.dta", clear sort id merge m:1 id using "C:\temp\B.dta"

Stata 10 and earlier

Use the .joinby command:

use "C:\temp\A.dta", clear sort id joinby id using "C:\temp\B.dta", unmatched(both)

Results

In both versions, the .merge command creates a variable _merge indicating the results. For example, the designation (3) in the column on the right means that the observation appears in both data sets and that they're matched:

+--------------------------------+ | id y x _merge | |--------------------------------| | 1 85 53 matched (3) | | 1 47 53 matched (3) | | 2 95 23 matched (3) | | 4 36 . master only (1) | | 5 83 . master only (1) | | 3 . 45 using only (2) | +--------------------------------+

For more about statistical and mathematical software, email the UITS Stat/Math Center, visit the center's web page, or phone 812-855-4724 (IUB) or 317-278-4740 (IUPUI). The center is located in Bloomington at 410 N. Park Avenue, and is open for consultation by appointment Monday-Friday 9am-5pm.

This is document azco in domain all.
Last modified on March 25, 2011.

Comments/Questions/Corrections

Use this form to offer suggestions, corrections, and additions to the Knowledge Base. We welcome your input!

If you are affiliated with Indiana University and would like assistance with a specific computing problem, please use the Ask a Consultant form, or contact your campus Support Center.

Contact Information

Note: We will reply to your comment at this address. If your message concerns a problem receiving email, please enter an alternate email address.