{smcl} {* *! version 0.5.6 10nov2026 Eric Booth}{...} {vieweralsosee "[D] merge" "help merge"}{...} {vieweralsosee "[D] append" "help append"}{...} {vieweralsosee "[D] joinby" "help joinby"}{...} {vieweralsosee "[D] frlink" "help frlink"}{...} {viewerjumpto "Quick start" "mergemap##quickstart"}{...} {viewerjumpto "Installation" "mergemap##install"}{...} {viewerjumpto "Syntax" "mergemap##syntax"}{...} {viewerjumpto "Description" "mergemap##description"}{...} {viewerjumpto "Reading the receipt" "mergemap##receipt"}{...} {viewerjumpto "Scan mode versus run mode" "mergemap##modes"}{...} {viewerjumpto "Drawing the map" "mergemap##draw"}{...} {viewerjumpto "Naming files so they map well" "mergemap##naming"}{...} {viewerjumpto "Options" "mergemap##options"}{...} {viewerjumpto "Examples" "mergemap##examples"}{...} {viewerjumpto "Joins in Stata and SQL" "mergemap##sql"}{...} {viewerjumpto "Flags and what to do about them" "mergemap##flags"}{...} {viewerjumpto "Putting a map in a document" "mergemap##embed"}{...} {viewerjumpto "Limitations" "mergemap##limits"}{...} {viewerjumpto "Stored results" "mergemap##results"}{...} {title:Title} {phang} {bf:mergemap} {hline 2} Map the merges, appends, and joins across your do-files {marker quickstart}{...} {title:Quick start} {pstd} If you have never run {bf:mergemap}, start here. This writes three small example do-files into a new folder, scans them, and shows you the output:{p_end} {phang2}{stata "mergemap demo":. mergemap demo}{p_end} {pstd} Then point it at your own work. Give it your do-files in the order you run them:{p_end} {phang2}{cmd:. mergemap 01_clean.do 02_merge.do 03_analyze.do}{p_end} {pstd} or point it at a folder and let it take the {cmd:.do} files in name order:{p_end} {phang2}{cmd:. mergemap build/}{p_end} {pstd} Nothing is executed. {bf:mergemap} reads your code the way you would read it, prints a numbered table of every join it found (the {bf:receipt}), and writes the same record to a small file (the {bf:journal}, {cmd:journal.tsv} unless you choose a name). Then draw it:{p_end} {phang2}{cmd:. mergemap draw}{p_end} {pstd} which renders the map in the Results window when it fits, and writes it as a self-contained HTML page when it does not.{p_end} {marker install}{...} {title:Installation} {pstd} From GitHub:{p_end} {phang2}{cmd:. net install mergemap, from("https://raw.githubusercontent.com/ericabooth/mergemap-stata-public/main/") replace}{p_end} {pstd} or from a copy of the repository on your machine:{p_end} {phang2}{cmd:. net install mergemap, from("/path/to/mergemap") replace}{p_end} {pstd} {cmd:mergemap} needs Stata 16 or later and nothing else: no Python, no LaTeX, and no external programs.{p_end} {pstd} The test battery is an ancillary file, so {helpb net install} does not place it. {helpb net get:net get mergemap} puts it in the current directory if you want to run it.{p_end} {marker syntax}{...} {title:Syntax} {p 8 17 2} {cmd:mergemap} [{cmd:scan}] {it:{help filename:dofile}} [{it:dofile} ...] [{cmd:,} {opt out(filename)} {opt fold:er(path)} {opt noreceipt}] {p 8 17 2} {cmd:mergemap check} {it:dofile} [{it:dofile} ...] [{cmd:,} {opt out(filename)} {opt fold:er(path)}] {p 8 17 2} {cmd:mergemap run} {it:dofile} [{it:dofile} ...] [{cmd:,} {opt out(filename)} {opt fold:er(path)} {opt ex:amples(#)} {opt nochecks} {opt warn(#)} {opt stop(#)}] {p 8 17 2} {cmd:mergemap draw} [{it:journalfile}] [{cmd:if} {it:exp}] [{cmd:,} {opt exp:ort(target)} {opt sav:ing(filename)} {it:draw_options}] {p 8 17 2} {cmd:mergemap sql} [{cmd:full}|{cmd:left}|{cmd:inner}|{cmd:fanout}|{cmd:joinby}|{cmd:append}|{cmd:cross}|{cmd:mm}] {p 8 17 2} {cmd:mergemap demo} [{it:foldername}] [{cmd:,} {opt fold:er(path)} {opt replace}] {p 8 17 2} {cmd:mergemap receipt} {it:journalfile} [{cmd:,} {opt check} {opt paths(how)} {opt root(folder)}] {p 8 17 2} {cmd:mergemap list} [{it:journalfile}] [{cmd:,} {opt full} {opt paths(how)} {opt root(folder)}] {p 8 17 2} {cmd:mergemap detail} {it:#} [{it:journalfile}] [{cmd:,} {opt draw}] {p 8 17 2} {cmd:mergemap export} [{it:journalfile}] [{cmd:,} {opt f:ormat(dta|csv|xlsx)} {opt sav:ing(filename)} {opt replace} {opt paths(how)} {opt root(folder)}] {p 8 17 2} {cmd:mergemap clear} {pstd} {it:dofile} may be a file name, a folder, or a pattern such as {cmd:0*.do}, and you may give several of any kind in one call: {cmd:mergemap build/ mask/ extra.do} scans two folders and then one file, in the order you list them. A folder contributes its {cmd:.do} files in name order, a pattern contributes its matches in name order, and a missing {cmd:.do} extension is supplied for you. {opt folder(path)} is the same thing written as an option; it exists for programs that assemble the call, and you will not usually need it.{p_end} {pstd} {it:journalfile} names a {bf:journal}: the file {cmd:mergemap} writes when it scans or runs your do-files, one line per thing it found. Each recorded thing, a join, a save, a {cmd:keep if}, is called an {bf:event}, and the receipt's numbers ({cmd:#1}, {cmd:#2}, ...) count them. Every other subcommand reads a journal back. Leave the name out and each subcommand uses the most recent journal, so the usual sequence is {cmd:mergemap build/} and then plain {cmd:mergemap draw}.{p_end} {synoptset 26 tabbed}{...} {synopthdr:subcommand} {synoptline} {synopt :{opt demo}}write a worked example, scan it, and show the output{p_end} {synopt :{opt scan}}read do-files without running them {it:(the default)}{p_end} {synopt :{opt check}}show only the events that were flagged{p_end} {synopt :{opt run}}run the do-files and record what actually happened{p_end} {synopt :{opt draw}}draw the map: Results window, HTML, PNG/SVG, mermaid, DOT{p_end} {synopt :{opt sql}}how each merge form pairs rows, with its name in SQL, R, and Python{p_end} {synopt :{opt receipt}}reprint the receipt from a saved journal{p_end} {synopt :{opt list}}the journal as a table; {opt full} for every column{p_end} {synopt :{opt detail} {it:#}}the journal's full record of event {it:#}; {opt draw} diagrams a join's row pairing{p_end} {synopt :{opt export}}the journal as a dataset or workbook: {cmd:.dta}, {cmd:.csv}, {cmd:.xlsx}{p_end} {synopt :{opt clear}}forget the remembered journal; files are never touched{p_end} {synoptline} {p2colreset}{...} {marker description}{...} {title:Description} {pstd} {cmd:mergemap} answers one question: how did this dataset get built? It reads a sequence of do-files, finds every {helpb merge}, {helpb append}, {helpb joinby}, {helpb cross}, {helpb frlink}, and {helpb frget}, along with the steps that change the shape of the data around them ({helpb reshape}, {helpb collapse}, {helpb contract}, {helpb xpose}, {helpb fillin}, {helpb duplicates}) and the steps that change how many rows you have ({cmd:keep if}, {cmd:drop if}), and reports them in the order your code performs them.{p_end} {pstd} Four words come up throughout this help file. An {bf:event} is one thing {cmd:mergemap} found in your code: a join, a reshaping step, a {cmd:keep} or {cmd:drop}, a {cmd:use}, or a {cmd:save}. The {bf:receipt} is the numbered table printed in the Results window, one row per event. The {bf:journal} is the same record written to a tab-separated file, one line per event with every column the receipt shows and more; every drawing, list, and export is produced by reading a journal back, which is why you can draw this week what you scanned last week. The {bf:map} is the drawing itself.{p_end} {pstd} The {cmd:keep} and {cmd:drop} statements are reported alongside the joins because they change the row count too. When a dataset comes out smaller than you expected, the cause is at least as often a {cmd:drop if} a few lines below the merge as the merge itself, and a report that shows both, in order, lets you compare them in one place.{p_end} {pstd} It does not write joins for you and it does not change your code. It describes work you have already done, which makes it useful in three moments: when you inherit someone else's project and need to see the shape of it, when a merge went wrong and you need to find where, and when you need a record of a data pipeline for a report or an appendix.{p_end} {marker receipt}{...} {title:Reading the receipt} {pstd} Every run prints a receipt first. It is a numbered index of what was found, one row per event, in the order the code performs them:{p_end} {p 8 8 2}{c TLC}{hline 72}{c TRC}{p_end} {p 8 8 2}{c |} {space 1}# {space 1}file{space 11}line{space 1}command{space 6}keys{space 6}using/result{space 6}F{space 1}flags{space 1}{c |}{p_end} {p 8 8 2}{c BLC}{hline 72}{c BRC}{p_end} {phang2} {bf:#} is the event number, and the order the events happen in.{p_end} {phang2} {bf:file} and {bf:line} say where in your code the event happens, so you can go fix it.{p_end} {phang2} {bf:command} is the Stata command with its form: {cmd:merge m:1}, {cmd:reshape wide}, and so on.{p_end} {phang2} {bf:keys} lists the variables the join matches on. Blank means the command does not take a key ({cmd:append}, {cmd:xpose}).{p_end} {phang2} {bf:using/result} is the file, tempfile, or frame being brought in, or, for a {cmd:save}, the file being written.{p_end} {phang2} {bf:F} marks {cmd:force}. Any mark in this column deserves a look: {cmd:force} tells Stata to proceed through a type mismatch it would otherwise refuse.{p_end} {phang2} {bf:flags} is the short version of anything suspicious. See {help mergemap##flags:Flags and what to do about them}.{p_end} {marker modes}{...} {title:Scan mode versus run mode} {pstd} {bf:Scan mode} is the default and it is safe: {cmd:mergemap} reads your do-files as text and never executes them. It works on code that will not currently run, on someone else's project, and on files whose data you do not have. What it cannot know is anything that only exists at run time, so there are no observation counts, no match counts, and no duplicate-key checks.{p_end} {pstd} {bf:Run mode} executes your do-files with instrumentation around each join and records what actually happened: observations in and out, the {cmd:_merge} breakdown, how many rows shared a key value on each side, and what share of each side found a partner. Your results are unchanged; the wrappers call the real commands and pass your options through untouched.{p_end} {pstd} Start with scan mode, which costs nothing and cannot break anything. Switch to run mode when you need the observed counts, or when a scanned map shows an unresolved macro or loop that only execution can fill in.{p_end} {marker draw}{...} {title:Drawing the map} {pstd} {cmd:mergemap draw} turns the most recent journal into a picture. With no argument it draws whatever the last {cmd:mergemap}, {cmd:mergemap run}, or {cmd:mergemap demo} recorded in this session; in a fresh session it falls back to {cmd:journal.tsv} in the working directory, which is where a scan writes by default. Name a journal file to draw anything else.{p_end} {pstd} {opt export()} picks the medium:{p_end} {synoptset 22 tabbed}{...} {synopt :{opt export(smcl)}}the Results window; the default{p_end} {synopt :{opt export(html)}}a self-contained page: no internet, no JavaScript{p_end} {synopt :{opt export(png)}}a picture through Stata's own graph engine{p_end} {synopt :{opt export(svg)}}the same drawing, scalable{p_end} {synopt :{opt export(mermaid)}}a text description of the diagram; see below{p_end} {synopt :{opt export(dot)}}the same in Graphviz's DOT language{p_end} {synopt :{opt export(erdiagram)}}mermaid text again, in a variant that lists each dataset's merge keys inside its box{p_end} {synoptline} {p2colreset}{...} {pstd} {bf:Mermaid} and {bf:DOT} are plain-text diagram languages: the export is a small text file that names the boxes and arrows, and other software draws it. Paste mermaid text into GitHub, Quarto, VS Code, or {browse "https://mermaid.live":mermaid.live} and it renders as a diagram with nothing installed; DOT is read by Graphviz and by several online viewers. Reach for these when you want the map inside a README, a Quarto document, or a wiki rather than as a separate image file. In a GitHub README, put the exported text in a fenced code block marked {cmd:```mermaid} and GitHub draws it.{p_end} {pstd} {bf:Reading it.} A box is a dataset: a file, a frame, or the data in memory at that point. The boxes run down a central column, the {bf:spine}, in the order your code touches them; joined-in files enter from the side, and arrows are the flow of data. {bf:[saved]} marks a file your code writes; a dashed box is a tempfile, and {bf:[tempfile from line 412]} says where it was made. A stacked box labelled {cmd:x4:} is a loop drawn once, naming its first and last file ({opt noellipsis} expands it); a file on the spine that a loop wrote shows {cmd:x4} after its name, and a loop that ran once shows the one file it resolved to. {cmd:keep} and {cmd:drop} steps appear as slim boxes on the spine, because a {cmd:drop if} explains a shrinking dataset at least as often as any merge. Counts in parentheses were dropped from the result, and {cmd:!!} marks anything worth a look, always as text, never as colour alone.{p_end} {pstd} {bf:Reading the HTML page.} Each box spends one line per fact. A file that is read and saved straight away, with nothing drawn between, is one box: the file's name, then {cmd:-> #4 saved:} and the name it was saved under. If you hid the filters between the read and the save with one of the options above, the two count lines in that box still betray them: rows in and rows saved differ. A filter or reshape puts its row change on its own line when it fits, {cmd:keep if price < 12000 . 74 -> 60 obs}; a flagged one reads {cmd:!! 209,634 -> 203,115 (-6,519, 3.1%)}. A join that matched every row says {cmd:all 40 matched, 100% of both sides} in one line; otherwise the {cmd:_merge} breakdown and {cmd:cover: 99.7% of master . 99.2% of using} follow, and the result {cmd:-> 8 x 63} sits at the end of the command line. Two markers are explained once, in the legend, instead of on every box they apply to: {cmd:~} after a name means the path was built from a macro and run mode resolves it; {cmd:x?} means a loop over a list built at run time, which run mode counts. Hover any box for its full record, including what the one-line forms leave out.{p_end} {pstd} {bf:When the map is too long.} Suppose your build is a real one: a dozen do-files that read raw files, trim them, and merge them into an analysis file. Scanning a build like that can record a few thousand events, and most of them are not joins. In one pipeline used to test this package, 3,092 events broke down as 2,527 {cmd:keep} and {cmd:drop} statements, 240 saves and re-reads of tempfiles inside a single program, and 63 joins, and the map of all of it came out about 208,000 pixels tall. Nothing needs to be thrown away to fix that: the journal and the receipt always keep every event, and what you control is the drawing. Each option below hides one kind of event from the map, the options combine, and {cmd:draw} prints a line saying exactly what it hid, so anyone reading the map knows it is a chosen view of the record, not the record:{p_end} {phang2}{cmd:. mergemap draw, nofilters}{p_end} {phang2}{cmd:. mergemap draw, norowfilters}{p_end} {phang2}{cmd:. mergemap draw, novarfilters}{p_end} {phang2}{cmd:. mergemap draw, notempfiles}{p_end} {phang2}{cmd:. mergemap draw, filesonly}{p_end} {phang2}{cmd:. mergemap draw if line < 400 & strpos(dofile, "01_")}{p_end} {pstd} {opt nofilters} hides every {cmd:keep} and {cmd:drop}; {opt norowfilters} hides only the row filters ({cmd:keep if}, {cmd:drop if}) and {opt novarfilters} only the variable lists ({cmd:keep varlist}, {cmd:drop varlist}), so you can keep the steps that change the row count and lose the ones that only trim columns. {opt notempfiles} hides saves to, uses of, and joins against a tempfile, which is most of what a loop inside a program produces. {opt notransforms} hides the reshaping steps ({cmd:reshape}, {cmd:collapse}, {cmd:contract}, {cmd:duplicates} and kin). {opt joinsonly} is {opt notransforms} plus {opt nofilters}; {opt filesonly} adds {opt notempfiles} to that and leaves the joins between named files, which is the picture of how the files on disk relate. Note that a join whose using side is a tempfile goes with {opt notempfiles}; when that join is the one you care about, use an {cmd:if} instead.{p_end} {pstd} The {cmd:if} is evaluated on the journal's own columns, with the count columns as numbers and the text columns as text, so it can page a long pipeline any way the journal can be sliced: by do-file ({cmd:if strpos(dofile, "mask")}), by line range ({cmd:if line >= 400}), by event kind ({cmd:if inlist(class, "join", "save")}), or by what happened ({cmd:if n_out < n_in}). The {cmd:dofile} column holds the do-file's name without its folder ({cmd:01_clean.do}, not {cmd:build/01_clean.do}), so slice by name. Column names are listed under {help mergemap##results:Stored results} and in the header of the journal file.{p_end} {pstd} {bf:When the labels are too long.} Run mode records the file paths it actually opened, so a map of a project stored under {cmd:C:\Users\me\Documents\projects\myproject\data\...} repeats that prefix in every box. {opt paths(base)} shows file names alone, {opt paths(parent)} the parent folder and the file name, and {opt paths(#)} the last {it:#} components. {opt root(folder)} cuts everything above a folder you name, so a path becomes relative to your project: with {opt root(myproject)} the example above reads {cmd:data\...}. Naming the project folder, instead of typing a prefix, means the same command gives the same labels on every machine the project is copied to, whatever folders hold it there. The same two options work for {cmd:mergemap receipt}, {cmd:mergemap list} and {cmd:mergemap export}.{p_end} {pstd} {bf:When the Results window is too small.} A window is a fixed-width space, so past {opt maxnodes(#)} join, reshape, and filter events (default 8), or whenever {opt layout(horizontal)} is asked for, the SMCL drawing steps aside: {cmd:draw} writes the HTML page instead, prints the path along with a clickable link that opens it, and opens it for you in GUI sessions unless {opt noopen}. {opt forcesmcl} overrides the count. When a PNG would be too dense for one readable image, {cmd:draw} splits it into one page per do-file and says so.{p_end} {marker naming}{...} {title:Naming files so they map well} {pstd} {cmd:mergemap} reads whatever you wrote, so a few habits when you name and arrange things make the map more useful. None of them are required, and none of them change how your code runs.{p_end} {phang2} {bf:Number your do-files in run order.} With {cmd:01_clean.do}, {cmd:02_merge.do}, {cmd:03_analyze.do}, the folder order is the run order, so {cmd:mergemap build/} gives you the pipeline in the sequence it happens. Without the numbers you have to list the files yourself and get the order right by hand.{p_end} {phang2} {bf:Give a loop a list Stata can read without running it.} A loop over a literal list or a numlist resolves during the scan, so four merges collapse into one stacked node naming the first and last file:{p_end} {phang3}{cmd:forvalues y = 2019/2022 {c -(}}{p_end} {phang3}{cmd: merge 1:1 id using acs_`y'.dta, nogenerate}{p_end} {phang3}{cmd:{c )-}}{p_end} {pstd} A loop over a list built while the code runs, from a directory listing or an {cmd:r()} result, cannot be counted without executing anything, so the map draws one node showing the unresolved name and flags it. Run mode resolves it. When you want the scan alone to be informative, prefer the literal list.{p_end} {phang2} {bf:Use one stub and vary only the index.} {cmd:acs_2019.dta} through {cmd:acs_2022.dta} collapse into {cmd:x4: acs_2019.dta ... acs_2022.dta}. Files called {cmd:acs19.dta}, {cmd:acs_2020_final.dta} and {cmd:ACS2021v2.dta} are three unrelated names, so they draw as three separate nodes. This is the habit that also makes {helpb reshape} work: a common stub with the varying part in one place.{p_end} {phang2} {bf:Keep raw and built files in separate folders.} Reading from {cmd:raw/} and writing to {cmd:built/} makes the sources and the outputs obvious in the map, and it lets {cmd:mergemap} tell you when two do-files write the same path.{p_end} {phang2} {bf:Save under a name that says what the file holds.} The box shows the name you chose, so {cmd:built/county_panel.dta} reads better in a figure than {cmd:temp2.dta}.{p_end} {marker options}{...} {title:Options} {dlgtab:Which files to read} {synoptset 26 tabbed}{...} {synopt :{opt fold:er(path)}}read the {cmd:.do} files in {it:path}, in name order{p_end} {synoptline} {p2colreset}{...} {pstd} You will usually not need {opt folder()}: a folder passed as the argument does the same thing, so {cmd:mergemap build/} and {cmd:mergemap, folder(build)} are equivalent.{p_end} {dlgtab:What to write} {synoptset 26 tabbed}{...} {synopt :{opt out(filename)}}write the journal here; default {cmd:journal.tsv}{p_end} {synopt :{opt noreceipt}}skip the receipt table{p_end} {synoptline} {p2colreset}{...} {pstd} The journal is a tab-separated file with one line per event, and every other output is built from it. Read it back with {helpb import delimited} to audit the joins yourself, or reprint the table with {cmd:mergemap receipt}.{p_end} {dlgtab:How loudly to complain} {synoptset 26 tabbed}{...} {synopt :{opt warn(#)}}mark an event {bf:warn} past this many unmatched rows{p_end} {synopt :{opt stop(#)}}mark it {bf:stop}, and return an error, past this many{p_end} {synoptline} {p2colreset}{...} {pstd} Both take either a count ({cmd:warn(500)}) or a share between 0 and 1 ({cmd:warn(.05)}, the default). Two percent unmatched is worth a note and forty percent is a crisis; one warning symbol cannot say which, so {cmd:mergemap} sorts events into {bf:note}, {bf:warn} and {bf:stop}. A {bf:stop} makes {cmd:mergemap run} exit with an error, which lets you put it in a master do-file as a gate that halts the build.{p_end} {pstd} Both options belong to {cmd:mergemap run}: a scan counts no rows, so it takes neither. {opt stop()} has no default, so without it no threshold produces a {bf:stop}. One event is a {bf:stop} whatever the thresholds say: a {cmd:merge m:m} with {opt force}, which pairs rows by position and lets the key types disagree, so a run containing one always ends with r(9).{p_end} {pstd} For a {cmd:merge}, the unmatched rows that count are the master-only rows. Using-only rows count as well when you ask for them: if {opt keep()} retains them ({cmd:keep(2)}, {cmd:keep(using)}, {cmd:keep(match using)}, or any abbreviation {cmd:merge} accepts), they are rows you chose to carry forward unmatched, and the share is then taken over the master rows plus those using-only rows. Without {opt keep()} the result also holds using-only rows, but they do not count toward {bf:warn} or {bf:stop}; the flag still reports them as {it:N} {cmd:using-only kept}.{p_end} {dlgtab:Run mode only} {synoptset 26 tabbed}{...} {synopt :{opt ex:amples(#)}}after each join, list up to {it:#} of its unmatched rows, keys and {cmd:_merge} only{p_end} {synopt :{opt nochecks}}skip the duplicate-key check on using files, which is faster on large files{p_end} {synoptline} {p2colreset}{...} {dlgtab:Draw only} {synoptset 26 tabbed}{...} {synopt :{opt sav:ing(filename)}}where to write; sensible defaults per medium{p_end} {synopt :{opt style(boxes|rail)}}Results-window style: full boxes (default), or {cmd:rail}, one line per event{p_end} {synopt :{opt lay:out(vertical|horizontal)}}down the page (default) or across it{p_end} {synopt :{opt maxnodes(#)}}how much SMCL will attempt before handing over to HTML{p_end} {synopt :{opt forcesmcl}}draw in the Results window regardless of size{p_end} {synopt :{opt compact}}one line per box (Results window); no count lines (HTML){p_end} {synopt :{opt nocounts} {opt nokeys} {opt noellipsis}}leave counts, keys, or loop detail out{p_end} {synopt :{opt notrans:forms}}hide {cmd:reshape}, {cmd:collapse}, {cmd:contract} and friends{p_end} {synopt :{opt nofilters}}hide every {cmd:keep} and {cmd:drop}, on rows or variables{p_end} {synopt :{opt norow:filters}}hide {cmd:keep if} and {cmd:drop if} only{p_end} {synopt :{opt novar:filters}}hide {cmd:keep varlist} and {cmd:drop varlist} only{p_end} {synopt :{opt notemp:files}}hide saves to, uses of, and joins against tempfiles{p_end} {synopt :{opt joinsonly}}{opt notransforms} and {opt nofilters}: the joins and nothing else{p_end} {synopt :{opt filesonly}}{opt joinsonly} and {opt notempfiles}: joins between named files{p_end} {synopt :{cmd:if} {it:exp}}draw the events for which {it:exp} is true, on the journal's columns{p_end} {synopt :{opt paths(how)}}{cmd:full} (default), {cmd:base}, {cmd:parent}, or a number of trailing components{p_end} {synopt :{opt root(folder)}}show every path relative to this folder{p_end} {synopt :{opt det:ails}}under the HTML map, a written record of each join (the hover text's facts, in prose), each folded until clicked{p_end} {synopt :{opt embed}}HTML as a fragment for someone else's page; see below{p_end} {synopt :{opt acc:ent(hex)}}the one colour used for flags and arrowheads{p_end} {synopt :{opt page(dofile)}}PNG/SVG as one image per do-file{p_end} {synopt :{opt wrap(#)}}label wrap width{p_end} {synopt :{opt replace}}overwrite a file named in {opt saving()}; the default {cmd:mergemap_map} images are always overwritten{p_end} {synopt :{opt noopen}}write the HTML but do not open the browser{p_end} {synoptline} {p2colreset}{...} {pstd} An image you name with {opt saving()} is yours: {cmd:export(png)} and {cmd:export(svg)} will not write over an existing {it:stub}{cmd:.png} or {it:stub}{cmd:.svg} (or any page's file, with one image per do-file) unless you add {opt replace}, and stop with r(602) instead, before any page is drawn. HTML, mermaid, dot and {cmd:mergemap export} already worked this way. Without {opt saving()} the images go to {cmd:mergemap_map.png} and {cmd:mergemap_map.svg}, which are overwritten on every draw so that you can redraw as often as you like.{p_end} {dlgtab:Receipt, list and export} {synoptset 26 tabbed}{...} {synopt :{opt check}}{cmd:receipt} only: print only the flagged events, as {cmd:mergemap check} does{p_end} {synopt :{opt paths(how)}}shorten the file labels, as for {cmd:draw}{p_end} {synopt :{opt root(folder)}}paths relative to a folder, as for {cmd:draw}{p_end} {synopt :{opt f:ormat(dta|csv|xlsx)}}{cmd:export} only; follows the extension of {opt saving()} when omitted{p_end} {synoptline} {p2colreset}{...} {pstd} {cmd:mergemap export} to {cmd:.xlsx} writes three sheets: {bf:events}, every event and every column, which is the receipt with nothing hidden; {bf:joins}, one row per join with its counts, {cmd:_merge} breakdown and coverage; and {bf:filters}, one row per {cmd:keep} or {cmd:drop} with the rows it removed and the percent that was. Count columns are numbers, so Excel sorts and filters them as numbers. The map can hide the filters while the workbook keeps all of them.{p_end} {dlgtab:Demo only} {synoptset 26 tabbed}{...} {synopt :{opt fold:er(path)}}write the example here; default {cmd:mergemap_demo}; quote a name that holds a space{p_end} {p2colreset}{...} {pstd} Running {cmd:mergemap demo} a second time refreshes the example in place, so you can retype it as often as you like. If the folder holds anything {cmd:mergemap} did not write, it stops and leaves your files alone; {opt replace} proceeds anyway. The demo's diagram is larger than the Results window draws, so it is written to {cmd:demo_map.html} in the same folder.{p_end} {synoptset 26 tabbed}{...} {synopt :{opt replace}}write the example into an existing folder that {cmd:mergemap} did not create{p_end} {synoptline} {p2colreset}{...} {marker examples}{...} {title:Examples} {pstd} The examples that write into a subfolder ({cmd:audit/}, {cmd:figures/}) assume that folder already exists; {cmd:mergemap} does not create folders.{p_end} {pstd}{bf:See it work, with no setup}{p_end} {phang2}{stata "mergemap demo":. mergemap demo}{p_end} {pstd}{bf:Map the do-files you run, in the order you run them}{p_end} {phang2}{cmd:. mergemap 01_clean.do 02_merge.do 03_analyze.do}{p_end} {pstd}{bf:Map a whole folder, in name order}{p_end} {phang2}{cmd:. mergemap build/}{p_end} {phang2}{cmd:. mergemap 0*.do}{p_end} {pstd}{bf:Just tell me what looks wrong}{p_end} {phang2}{cmd:. mergemap check build/}{p_end} {pstd}{bf:Keep the journal somewhere I choose, and skip the table}{p_end} {phang2}{cmd:. mergemap build/, out(audit/joins.tsv) noreceipt}{p_end} {pstd}{bf:Run it for real and get the counts}{p_end} {phang2}{cmd:. mergemap run 01_clean.do 02_merge.do 03_analyze.do}{p_end} {pstd}{bf:Run it and show me five example rows per join}{p_end} {phang2}{cmd:. mergemap run build/, examples(5)}{p_end} {pstd}{bf:Use it as a gate: stop the master do-file if a join loses too much}{p_end} {phang2}{cmd:. mergemap run build/, warn(.02) stop(.10)}{p_end} {pstd}{bf:Skip the duplicate-key check on very large using files}{p_end} {phang2}{cmd:. mergemap run build/, nochecks}{p_end} {pstd}{bf:Draw what I just scanned}{p_end} {phang2}{cmd:. mergemap draw}{p_end} {pstd}{bf:Just the joins: no reshapes, no collapses, no keep or drop steps}{p_end} {phang2}{cmd:. mergemap draw, joinsonly}{p_end} {pstd}{bf:Keep the filters but drop the reshaping steps, or the reverse}{p_end} {phang2}{cmd:. mergemap draw, notransforms}{p_end} {phang2}{cmd:. mergemap draw, nofilters}{p_end} {pstd}{bf:Keep the row filters, which change the counts, and lose the column trims}{p_end} {phang2}{cmd:. mergemap draw, novarfilters}{p_end} {pstd}{bf:The files on disk and how they relate: no filters, no reshapes, no tempfiles}{p_end} {phang2}{cmd:. mergemap draw, filesonly export(html) saving(files.html) replace}{p_end} {pstd}{bf:A long pipeline one page at a time, cut by do-file name and line}{p_end} {phang2}{cmd:. mergemap draw if strpos(dofile, "01_") & line < 400, filesonly export(html) saving(step1.html) replace}{p_end} {phang2}{cmd:. mergemap draw if !(strpos(dofile, "01_") & line < 400), filesonly export(html) saving(main.html) replace}{p_end} {pstd}{bf:Only the joins that lost rows}{p_end} {phang2}{cmd:. mergemap draw if class == "join" & n_out < n_in}{p_end} {pstd}{bf:Short labels: file names only, or relative to the project folder}{p_end} {phang2}{cmd:. mergemap draw, paths(base)}{p_end} {phang2}{cmd:. mergemap draw, root(myproject) export(html) saving(map.html) replace}{p_end} {pstd}{bf:The HTML map with the count lines left out}{p_end} {phang2}{cmd:. mergemap draw, export(html) compact nokeys saving(thin.html) replace}{p_end} {pstd}{bf:Map a numbered folder of do-files, then draw only its joins}{p_end} {phang2}{cmd:. mergemap build/}{p_end} {phang2}{cmd:. mergemap draw, joinsonly export(png) saving(figures/joins) replace}{p_end} {pstd}{bf:A figure for a report}{p_end} {phang2}{cmd:. mergemap draw, export(png) saving(figures/pipeline) replace}{p_end} {pstd}{bf:A figure for a slide, wider than it is tall}{p_end} {phang2}{cmd:. mergemap draw, export(html) layout(horizontal) saving(pipeline.html) replace}{p_end} {pstd}{bf:The compact look, forced into the Results window}{p_end} {phang2}{cmd:. mergemap draw, style(rail) forcesmcl}{p_end} {pstd}{bf:Text I can paste into a GitHub README or a Quarto document}{p_end} {phang2}{cmd:. mergemap draw, export(mermaid) saving(pipeline) replace}{p_end} {pstd}{bf:A fragment for a webdoc2 report, with the written record of each join folded in ({opt details})}{p_end} {phang2}{cmd:. mergemap draw, export(html) saving(pipe_frag.html) embed details replace}{p_end} {pstd}{bf:Show me what a joinby actually does to row counts}{p_end} {phang2}{stata "mergemap sql joinby":. mergemap sql joinby}{p_end} {pstd}{bf:Reprint a receipt from a journal I saved earlier}{p_end} {phang2}{cmd:. mergemap receipt audit/joins.tsv}{p_end} {pstd}{bf:The journal as a table, then one event in depth, drawn with its counts}{p_end} {phang2}{cmd:. mergemap list}{p_end} {phang2}{cmd:. mergemap detail 4, draw}{p_end} {pstd}{bf:The journal as a dataset, to audit or graph yourself}{p_end} {phang2}{cmd:. mergemap export, saving(joins.dta) replace}{p_end} {pstd}{bf:The same as a workbook: every event, the joins, and the filters on three sheets}{p_end} {phang2}{cmd:. mergemap export, saving(joins.xlsx) replace root(myproject)}{p_end} {pstd}{bf:A receipt with file names only}{p_end} {phang2}{cmd:. mergemap receipt audit/joins.tsv, paths(base)}{p_end} {marker sql}{...} {title:Joins in Stata and SQL} {pstd} If you have met joins in SQL, R, or Python, this table maps them onto Stata. It is also the fastest way to see what Stata's forms actually do.{p_end} {synoptset 34}{...} {synopthdr:Stata} {synoptline} {synopt :{cmd:merge 1:1} {it:k} {cmd:using} B}full outer join; every row from both sides{p_end} {synopt :{cmd:merge 1:1} {it:k} {cmd:using} B{cmd:, keep(3)}}inner join; matched rows only{p_end} {synopt :{cmd:merge 1:1} {it:k} {cmd:using} B{cmd:, keep(1 3)}}left join; all master rows{p_end} {synopt :{cmd:merge 1:1} {it:k} {cmd:using} B{cmd:, keep(2 3)}}right join; all using rows{p_end} {synopt :{cmd:merge 1:1} {it:k} {cmd:using} B{cmd:, keep(1)}}anti join; master rows with no match{p_end} {synopt :{cmd:merge m:1} {it:k} {cmd:using} B}a lookup; many rows pull one row each{p_end} {synopt :{cmd:merge 1:m} {it:k} {cmd:using} B}a fan-out; one row becomes many{p_end} {synopt :{cmd:merge m:m} {it:k} {cmd:using} B}{bf:not a join}; see below{p_end} {synopt :{cmd:joinby} {it:k} {cmd:using} B}the real many-to-many; all pairs within key{p_end} {synopt :{cmd:cross using} B}cross join; every row against every row{p_end} {synopt :{cmd:append using} B}union; stacks rows, matching variables by name{p_end} {synopt :{cmd:frlink m:1} {it:k}{cmd:, frame(}B{cmd:)}}declares the relationship; moves nothing yet{p_end} {synopt :{cmd:frget} {it:v}{cmd:, from(}{it:link}{cmd:)}}pulls columns along that relationship{p_end} {synopt :{cmd:collapse (mean)} {it:x}{cmd:, by(}{it:k}{cmd:)}}aggregate; one row per group{p_end} {synopt :{cmd:reshape long}/{cmd:wide}}unpivot and pivot{p_end} {synoptline} {pstd} {cmd:mergemap sql} prints this table in the Results window. Follow it with one of {cmd:full}, {cmd:left}, {cmd:inner}, {cmd:fanout}, {cmd:joinby}, {cmd:append}, {cmd:cross}, or {cmd:mm} and it adds a worked example of that form: two toy tables of a few rows each, the command between them, and the result, with lines showing which row paired with which and a rule underneath for how many rows come out. The subcommand is named {cmd:sql} because the join vocabulary most teams share ({it:left join}, {it:inner join}, and the rest) comes from SQL; nothing about it requires SQL, and it never touches your data.{p_end} {pstd} The same diagram is available for your own joins. {cmd:mergemap detail} {it:#}{cmd:, draw} takes event {it:#} from the journal and draws its row pairing with the observed counts in place of the toy rows, so you can see, for example, where event 3's 533 master-only rows sit. If the event comes from a scan there are no counts to draw, and the worked example for its form is shown instead, with a note saying why.{p_end} {pstd} Venn diagrams are a popular way to explain joins and they are the wrong picture. A join is not a set operation on shared elements; it is every pairing of rows from two tables, filtered by a condition. That is why a join can return {it:more} rows than either input, which no Venn diagram can show. {cmd:mergemap} draws rows and arrows for this reason.{p_end} {marker flags}{...} {title:Flags and what to do about them} {phang} {bf:!! m:m} {space 2}{cmd:merge m:m} is not a join. It pairs the first master row having a key with the first using row having that key, the second with the second, and so on, which depends on the order your data happen to be in. If you want all pairings, use {helpb joinby}. If you meant a lookup, use {cmd:m:1}. If you did not know your key had duplicates, run {cmd:duplicates report} on it.{p_end} {phang} {bf:!! force} {space 2}{opt force} lets Stata push past a type mismatch, for example a variable stored as a string in one file and numeric in the other. The merge succeeds and the values may be wrong. Check the variable named in the flag.{p_end} {phang} {bf:!! merge failed} {space 2}The pipeline stopped at this event, and the flag carries Stata's error code. On a {cmd:1:1} or {cmd:m:1} merge the commonest cause is a key that is not actually unique on the side you declared unique; {cmd:duplicates report} on the key will show it. Run mode also records how many rows share a key value on each side ({cmd:dup_master} and {cmd:dup_using} in the journal, {cmd:dup-key obs} on the map), so you can see the problem coming on the merges that did not fail.{p_end} {phang} {bf:!! unmatched} {space 2}Rows did not find a partner. This is often fine and sometimes the whole bug. The flag reports which side they came from and how many.{p_end} {phang} {bf:!! dropped} {space 2}A {opt keep()} option removed rows from the result. The count appears in parentheses so you can see what left.{p_end} {phang} {bf:!! type} {space 2}The key is stored differently on the two sides, for example {cmd:id: str6 vs long}. Stata will refuse the merge, or {opt force} will let it through and the match will be wrong. This is the quietest way a merge fails.{p_end} {phang} {bf:!! also saved by} {space 2}This {cmd:save} writes to a file that another line, named in the flag, also writes. When both run, the second save replaces the first save's output, and anything that reads the file gets whichever version was written most recently. Usually one of the two saves is left over from an older draft of the code: rename one target, or delete the save you no longer mean.{p_end} {phang} {bf:!! stale} {space 2}A saved dataset is older than something it was built from, so it does not reflect the current code or the current inputs. {cmd:mergemap} only reports this; rebuilding is {helpb project:project}'s job.{p_end} {marker coverage}{...} {title:Counts, and why coverage is better} {pstd} In run mode each join reports how the rows resolved, and also what share of each side took part: {it:94% of master matched, 61% of the crosswalk never used}. Raw counts do not tell you whether 500 unmatched rows are a rounding error or a catastrophe, and they do not tell you that most of a lookup table went unused, which usually means the key is wrong. Shares do.{p_end} {pstd} {cmd:mergemap} also reports the most common unmatched key values, because 500 unmatched rows spread over 500 keys is a different problem from 500 rows sharing one key.{p_end} {marker embed}{...} {title:Putting a map in a document} {pstd} For Word or LaTeX, use {cmd:draw, export(png)} or {cmd:export(svg)} and insert the file as a figure. Vertical layout suits a page and horizontal suits a slide. A long pipeline reads better as one image per do-file: ask for that with {opt page(dofile)}, and {cmd:draw} does it unasked when one image would be too dense to read.{p_end} {pstd} For an HTML report, {cmd:export(html)} writes a self-contained page: no internet, no JavaScript, nothing to install. Inside a {cmd:webdoc} or {cmd:webdoc2} report, add {opt embed} to get a fragment instead: a stylesheet scoped so it cannot restyle the report around it, and a drawing that scales with the text column. Drop it into the document body and it flows and prints with the report.{p_end} {pstd} For a README, a wiki, or a Quarto document, {cmd:export(mermaid)} and {cmd:export(dot)} write text that renders with nothing installed: GitHub, Quarto, and VS Code draw mermaid natively, and online viewers cover DOT for anyone without Graphviz. {cmd:export(erdiagram)} writes mermaid's entity-relationship flavour, where the merge keys become attributes and the cardinalities become crow's-foot glyphs.{p_end} {pstd} A horizontal diagram is wider than any text column. Let it keep its own width and scroll sideways. Squeezed into a text column its labels fall below two pixels.{p_end} {marker limits}{...} {title:Limitations} {phang2} In scan mode, anything built at run time stays unresolved. A file name assembled from a macro appears as it is written in your code, and a loop over a list built from a directory listing cannot be counted. {cmd:mergemap} flags both, and run mode resolves them.{p_end} {phang2} The scanner matches command names in your source, so a join it never sees by name stays off the map. That covers a join performed inside a command you wrote yourself, and a join built up as text and then executed.{p_end} {phang2} A command behind a {cmd:by}, {cmd:bys}, {cmd:bysort} or {cmd:frame} {it:name} prefix ({cmd:bysort id: keep if _n == 1}, {cmd:frame f: merge 1:1 id using x}) is recorded in scan mode like any other, with the prefix named in its flags. Run mode does not instrument it, because the wrappers that count rows are not byable and do not follow another frame: it runs the line unchanged and journals a {bf:note} event in its place, with no counts, so the rows a {cmd:bysort id: keep if} removes show up only as a lower count at the next event. Statements inside a {cmd:frame} {it:name} {cmd:{c -(} ... {c )-}} block are recorded and, in run mode, instrumented as usual, flagged {cmd:inside a frame} {it:name} {cmd:block}; neither mode tracks which frame holds the data, so the map draws them as steps on the working data. {cmd:frame change}, {cmd:cwf} and {cmd:frame copy} are not followed.{p_end} {phang2} {cmd:mergemap run} rewrites your do-files into temporary copies with instrumented command names, keeping your line numbers. It does not alter your files. If a do-file uses {cmd:#delimit ;}, the scan is best-effort and says so.{p_end} {phang2} Do not nest {cmd:mergemap run} inside {cmd:webdoc do}. Both take control of how a do-file is executed.{p_end} {phang2} On Stata 16, run mode cannot hold the sort seed steady, because {cmd:c(sortseed)} came in after that release. The instrumentation's own bookkeeping advances Stata's sort RNG, so a later {cmd:sort} or {cmd:collapse} that breaks a tie at random can resolve differently than it would in a plain run. The gap shows up below display precision, and run mode says so when it starts. Scan mode, the default, does not execute anything and is unaffected. On a newer Stata, run mode restores the seed and the output is identical to a plain run, which the transparency test in the package's GitHub repository ({cmd:tests/runmode/transparency.do}) checks.{p_end} {marker results}{...} {title:Stored results} {pstd}{cmd:mergemap} stores the following in {cmd:r()}:{p_end} {synoptset 22 tabbed}{...} {p2col 5 22 26 2: Scalars}{p_end} {synopt:{cmd:r(N_events)}}number of events recorded{p_end} {synopt:{cmd:r(N_joins)}}number of joins{p_end} {synopt:{cmd:r(N_flags)}}number of flagged events{p_end} {synopt:{cmd:r(N_stop)}}number of events at severity {bf:stop}{p_end} {synopt:{cmd:r(N_warn)}}after {cmd:run}: number of events at severity {bf:warn}{p_end} {synopt:{cmd:r(n_pages)}}after {cmd:draw, export(png|svg)}: images written, one per page{p_end} {p2col 5 22 26 2: Macros}{p_end} {synopt:{cmd:r(journal)}}path to the journal file; after {cmd:draw}, always the journal you named (or the remembered one), even when a filter drew a cut copy{p_end} {synopt:{cmd:r(drawn)}}after {cmd:draw}: the journal the renderer actually read. After {cmd:if}, {opt nofilters}, {opt notempfiles}, {opt joinsonly}, {opt paths()}, {opt root()} and the like, this is a cut copy of {cmd:r(journal)} written to {cmd:c(tmpdir)}, so copy it if you want to keep it; otherwise it equals {cmd:r(journal)}{p_end} {synopt:{cmd:r(files)}}do-files scanned{p_end} {synopt:{cmd:r(output)}}after {cmd:draw}: the file it wrote; with several, the first of the format asked for{p_end} {synopt:{cmd:r(files)}}after {cmd:draw} to png, svg, mermaid, dot or erdiagram: every file written, such as {it:stub}{cmd:_td.mmd} and {it:stub}{cmd:_lr.mmd}, or one {it:stub}{cmd:_}{it:dofile}{cmd:.png} per page{p_end} {synopt:{cmd:r(hidden)}}after {cmd:draw}: what the options and the {cmd:if} left out, in words{p_end} {synopt:{cmd:r(file)}}after {cmd:export}: the dataset or workbook it wrote, with its extension{p_end} {p2colreset}{...} {pstd} {cmd:mergemap run} leaves these results in place even when it returns an error, whether the pipeline itself failed or an event crossed {opt stop()}, so a script can capture the run and then test {cmd:r(N_stop)}. The journal the run wrote also becomes the default for a later {cmd:mergemap draw}, {cmd:list}, {cmd:detail} or {cmd:export}.{p_end} {pstd} The journal's columns, for an {cmd:if} on {cmd:mergemap draw} and for your own reading of the file: {cmd:seq dofile line class cmd subtype keys master usingfile result} {cmd:n_in k_in n_using k_using n_out k_out m1 m2 m3 m4 m5 dup_master dup_using} {cmd:force opts loop_n loop_first loop_last severity keytypes cover_master} {cmd:cover_using lifecycle flags}. {cmd:class} is one of {cmd:source join link transform filter save flow note} ({cmd:source} is a {cmd:use} or import, {cmd:link} an {cmd:frlink} or {cmd:frget}, {cmd:flow} a {cmd:do}, {cmd:preserve}, {cmd:restore}, or {cmd:cd}, and {cmd:note} anything else kept for context, such as a {cmd:#delimit} region); a filter's {cmd:subtype} is {cmd:if} for a row filter and empty for a variable list; {cmd:opts} holds a filter's condition; {cmd:m1} through {cmd:m5} are the {cmd:_merge} counts; {cmd:usingfile} and {cmd:result} hold file paths, {cmd:tempfile:}{it:name}, or {cmd:frame:}{it:name}.{p_end} {marker related}{...} {title:Related commands} {pstd} {cmd:mergemap} describes joins that have already been written. These commands do neighbouring jobs, and for some questions one of them is the better tool.{p_end} {phang2} {bf:Before you combine files.} {cmd:precombine} (Chatfield, {it:Stata Journal} 15(3), and cited in {bf:[D] merge}) compares two or more datasets you are about to combine: which variables they share, which are unique to one file, and whether their value-label code sets agree. That is a pre-flight check; {cmd:mergemap} is a map of the flight afterwards. Use both.{p_end} {phang2} {bf:To manage a project's build.} {cmd:project} (Picard) tracks which do-files depend on which files and re-runs only what changed. {cmd:mergemap} reports when an output looks stale but never rebuilds anything; that is {cmd:project}'s job.{p_end} {phang2} {bf:To assert a specific number of dropped observations.} {cmd:iedropone} (DIME's {cmd:ietoolkit}) drops observations and errors unless exactly the expected number went. {cmd:mergemap} reports what happened; {cmd:iedropone} enforces what should.{p_end} {phang2} {bf:For participant-flow figures.} {cmd:flowchart} (Dodd) draws CONSORT and PRISMA diagrams of how subjects were included and excluded. It charts participants where {cmd:mergemap} charts datasets, and it needs LaTeX.{p_end} {phang2} {bf:For a row-flow picture.} {cmd:sankey} (Naqvi) draws flow widths from {cmd:from}/{cmd:to}/{cmd:value} data, which {cmd:mergemap} can export.{p_end} {phang2} {bf:Note on merge wrappers.} If your code uses {cmd:mmerge}, {cmd:dmerge}, {cmd:mergeall}, {cmd:pullin}, or a merge command of your own, that join does not appear on the map at all: the scanner matches Stata's own command names, and a command it does not know contributes nothing. Nothing warns you, so on a project that uses a wrapper, expect the map to understate the joins.{p_end} {title:Also see} {psee} Manual: {manlink D merge}, {manlink D append}, {manlink D joinby}, {manlink D frlink} {psee} Help: {manhelp merge D}, {manhelp append D}, {manhelp joinby D}, {manhelp frlink D}, {manhelp frget D}, {manhelp reshape D}, {manhelp collapse D} {title:Author} {pstd}Eric A. Booth{break} Sr Researcher, Texas 2036{break} eric.a.booth@gmail.com{p_end} {pstd} MIT License. Report issues at the {browse "https://github.com/ericabooth/mergemap-stata-public":GitHub repository}.{p_end}