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   Nick Cox <>
Subject   Re: st: code for merging data
Date   Mon, 21 Jan 2013 09:45:19 +0000

Daniel gave excellent advice on technique, to which I will add a few
comments, restating the main point in another way.

Skip ahead to the last iteration of your loop for l = 9. On that iteration, you

use lev3_1
merge commonid using lev9_1
capture merge using `mydata'
save using `mydata', replace

As the result is just the merge of 3 and 9, it is clear that the
command you -capture- is the one that failed, but the effect of
-capture- is that you suppressed the error message which could have
been informative.


On Mon, Jan 21, 2013 at 8:42 AM, daniel klein <> wrote:

> 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
> clear
> [...]
> 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-.

Prakash Singh

> 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
> clear
> 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