Bookmark and Share

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


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

st: Renumbering variables in a loop of files


From   Florian Seliger <[email protected]>
To   [email protected]
Subject   st: Renumbering variables in a loop of files
Date   Fri, 17 Dec 2010 22:15:20 -0700

Dear Statalist,

I have again a question concerning numbering  IDs in a foreach loop.

I have multiple datafiles for that I have specified a foreach loop.
Each dataset either contains a variable id_1, id_2, id_3, etc. or only a variable id without a number.

My goal is to assign a number to all IDs in each file. The numbers should  reflect the number of the file, e.g.

file no.		old	variable	--->	new variable
1			id_1			id_1
2			id_2			id_2
3			id_3			id_3
4			id				id_4
5			id_4			id_5
6			id_5			id_6
7			id				id_7
8			id_6			id_8
...			...				...	.

I have specified a command such as the following:

local i=1
foreach file ... {

use "`file'", clear

forvalues j=1(1)230  {  //230 is the number of files
capture confirm id_`j' 

if _rc==0 {
sort id_`j'
 capture rename id_`j' id_`i' 
		}
		}

else {
 sort id
 rename id id_`i'
}
			
			
local ++i
save "`file'", replace
		}

***end command***

With this command, STATA tells me for the first file that id_1 is already defined and stops the loop although I have used a second  "capture" before "rename".
Do you have an idea how I have to rewrite the command?

Thank you very much.
Best wishes,
Florian


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


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