Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: code for merging data

From   daniel klein <>
Subject   Re: st: code for merging data
Date   Mon, 21 Jan 2013 09:42:07 +0100


in your code you reload <lev3_1.dta> each iteration of the
(unnecessary, see below) loop. Now, I am not sure this causes the
trouble, but it seems kind of odd. Also, saving a temporary file
permanently seems no good idea, and this might indeed cause problems,
if this temporary file is not saved in the directory where the <lev_>
files are.

If the problem is not with one of the above mentioned, I cannot tell
what is wrong with the files that are not merged, but maybe Stata can
-- if you remove the -capture- prefix from your code.

I think in general -capture- is best used if you anticipate _one_
specific error to occur. Even in this case you want to make sure you
-capture- only this error, by checking the return code, or at least
you -capture noisily-.

Note that the old -merge- allows many files to be merged in one line,
so the loop should not be needed for that. You could use it to setup
the filenames. In this case code

forv j = 4/9 {
    loc fn `fn' lev`j'_1.dta
u lev3_1.dta
mer commonid using `fn'
sa mydata ,replace

Note that -forvalues- is faster and cleaner than -foreach- with -of numlist-.

Dear stata listers
I need help in correcting my programming code to merge data set. I am
using stata 10.

I have 7 stata data files which I need to merge. I wrote code for this
but it is only merging last data file to the first one. Please suggest
me something on this, my code is

set mem 700m
set more off
tempfile mydata
foreach l of numlist 4/9 {
   use lev3_1.dta
   merge commonid using lev`l'_1.dta
   capture merge using `mydata'
   ren _merge merge3_`l'
   save `mydata', replace

Please suggest me that where is the mistake happening in this code.
*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index