Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | Maarten Buis <maartenlbuis@gmail.com> |
To | statalist@hsphsun2.harvard.edu |
Subject | Re: st: automatic joining variables after merging datasets |
Date | Thu, 2 May 2013 09:16:17 +0200 |
On Wed, May 1, 2013 at 11:17 AM, Jörg Eulenberger wrote: > is the a automatic way to find variables with the exact same varlabel > and then copy the value from the second variable to the first variable? Here is one solution: *------------------ begin example ------------------ //---------------------- create two example datasets tempfile 1 2 sysuse auto, clear gen byte dataset = 1 save `1' // change the variable names in dataset 2 by adding // a random integer as suffix to the name sysuse auto, clear gen byte dataset = 2 foreach var of varlist * { rename `var' `var'`=ceil(6*runiform())' } save `2' //---- step 1: collect variable names and var labels tempfile varlab1 varlab2 use `1', clear desc, replace keep name varlab save `varlab1' use `2', clear desc, replace keep name varlab rename name name2 save `varlab2' //---------- step 2: find varnames with same varlabs merge 1:1 varlab using `varlab1', keep(match) //-------------- step 3: create do file that renames // the variables in dataset 2 tempname myfile tempfile tfile file open `myfile' using "`tfile'", write text replace forvalues i = 1/`=_N' { file write `myfile' "rename " (name2[`i']) " " (name[`i']) _n } file close `myfile' //--------- step 4: apply that .do file to dataset 2 use `2', clear do `tfile' //-------------------- step5: append dataset 1 and 2 append using `1' *------------------- end example ------------------- (For more on examples I sent to the Statalist see: http://www.maartenbuis.nl/example_faq ) --------------------------------- Maarten L. Buis WZB Reichpietschufer 50 10785 Berlin Germany http://www.maartenbuis.nl --------------------------------- * * For searches and help try: * http://www.stata.com/help.cgi?search * http://www.stata.com/support/faqs/resources/statalist-faq/ * http://www.ats.ucla.edu/stat/stata/