Hello,

I am new to stata and I can't figure out how to use loop (if it is the case) for the following. I need to generate 32 new .csv files for each departament from a main data base(.dta), BUT, before i need to make some changes.


The main data base cointain information for 1.020 cities from 32 departaments, looks like this: Both "code_city_a" and "code_city_b" go from 1 until 1.120, that means this is a matrix of 1.020*1.020

code_city_a code_city_b department_city_a department_city_b Coeficient
3 1 012 456 1
3 2 012 356 0,479
3 3 012 012 0
3 4 012 976 0,735


I need to generate a ,cvs file for all 32 departaments, filtering by "departament_city_a" and "departament_city_b", BUT each "code_city_*" should be listed from 0. In an example for departament==012 results should looks like this. Matrix of 320*320 (number of cities in that specific departament)



code_city_a code_city_b department_city_a department_city_b Coeficient
0 0 012 012 0
0 1 012 012 0,777
0 2 012 012 0,666
0 3 012 012 0,374

I was thinking this.
Example for departament "012"


Code:
use "C:\General.dta"
keep if departament_city_a==012
keep if departament_city_b==012 
sort code_city_a code_city_b
egen id = group(code_city_a)
replace id = id - 1
egen id2 = group(code_city_b)
replace id2 = id2 - 1
drop code_city_a drop_city_b
export delimited using "C:\finalj.csv",
But it may exists other easier and shorter way using loops. Can you help me?

Thanks