Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.

# st: Foreach looping code for generating a Quantiles variable for each two digit sic code

 From Jaime Laird To StataList LP Subject st: Foreach looping code for generating a Quantiles variable for each two digit sic code Date Thu, 16 Feb 2012 15:14:54 -0600

```I have search the appropriate places and have not seen my particular question addressed so I hoping I will add something to the list with this question. Forgive me if I have missed something.

What I need to do:

I need to plot the Quartiles for each two-digit Siccode in my data and it also need to be done by year. I have successfully found the code to do this but I would like to better understand looping to streamline tasks such as these.

The following code gives the results I need (I downloaded this SSC from within Stata, it is called egenmore):

egen resremRDq96 = xtile (resremRD), by (twodigit), if Year ==96, nquantiles(4)
egen resremRDq97 = xtile (resremRD), by (twodigit), if Year ==97, nquantiles(4)
egen resremRDq98 = xtile (resremRD), by (twodigit), if Year ==98, nquantiles(4)
egen resremRDq99 = xtile (resremRD), by (twodigit), if Year ==99, nquantiles(4)
egen resremRDq2000 = xtile (resremRD), by (twodigit), if Year ==2000, nquantiles(4)
egen resremRDq2001 = xtile (resremRD), by (twodigit), if Year ==2001, nquantiles(4)
egen resremRDq2002 = xtile (resremRD), by (twodigit), if Year ==2002, nquantiles(4)
egen resremRDq2003 = xtile (resremRD), by (twodigit), if Year ==2003, nquantiles(4)
egen resremRDq2004 = xtile (resremRD), by (twodigit), if Year ==2004, nquantiles(4)
egen resremRDq2005 = xtile (resremRD), by (twodigit), if Year ==2005, nquantiles(4)
egen resremRDq2006 = xtile (resremRD), by (twodigit), if Year ==2006, nquantiles(4)
egen resremRDq2007 = xtile (resremRD), by (twodigit), if Year ==2007, nquantiles(4)
egen resremRDq2008 = xtile (resremRD), by (twodigit), if Year ==2008, nquantiles(4)
egen resremRDq2009 = xtile (resremRD), by (twodigit), if Year ==2009, nquantiles(4)

A member here gave me a code to help loop my regressions and I tried to adapt it to work with these quantiles but was unsuccessful. Here is the code I tried to make from his:

forv y=1995/2009 {
if `y'<2000 loc yr=substr("`y'",3,2)
else loc yr `y'
qui levelsof twodigit if !mi(rd`yr'), loc(ts)
foreach t of loc ts {
xtile resremRDq`yr' = resremRD`yr', nquantiles(4)
}
}

The results only formed one new variable named "resremrdq95" and it did not assign the Quartiles by siccode (twodigit).

It also returns this error:

run "/var/folders/aL/aLs0EaEHFfCArViD4qvSeU+++TI/-Tmp-//SD07955.000000"