I am having a dataset in wide format for almost 80 years for 100 countries for about 200 variables. Variables bring the 3-letter ISO country code as their first component. I would need to reorder the variables in two different ways, with probably two loops.



The first is to order everything, grouping by each variable separately. In the example, below, that will be like:
Code:
 
  ts FRA_u DEU_u GBR_u USA_u FRA_size  DEU_size  GBR_size USA_size FRA_Δprdm DEU_Δprdm GBR_Δprdm USA_Δprdm

And the second to order everything by country code, similar to :

Code:
ts FRA_u FRA_size FRA_u FRA_Δprdm DEU_u  DEU_size DEU_Δprdm GBR_u GBR_size GBR_Δprdm  USA_u USA_size USA_Δprdm
I will need now two different reordering loops in order to produce my final results.
For more than 100 countries, a reordering for each one is time-consuming



The following is an example sample created just for this purpose. Variables do follow a random order, and as said above, there are more than 200 for more than 100 countries

I have been greatly benefited from this forum every time I posted a question and cannot thank enough!

Best,
Mario


Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float(ts DEU_u DEU_size DEU_Δprdm FRA_u FRA_size FRA_Δprdm GBR_u GBR_size GBR_Δprdm USA_u USA_size USA_Δprdm)
2000  7.92 19.044518         0 10.22  22.32587  .08333331 5.56 16.809107        0 3.99  14.02601         0
2001  7.77 18.948927         0  8.61 22.141853   .1547619  4.7 17.468409        0 4.73 14.528614         0
2002  8.48  19.23157 .08333331   8.7  22.72115          0 5.04 18.273579        0 5.78 15.041862         0
2003  9.78  19.32564         0  8.31 23.143427          0 4.81  18.95393 .0714286 5.99 15.246542         0
2004 10.73  18.81738         0  8.91 23.044697          0 4.59 19.572525        0 5.53  15.16888         0
2005 11.17  18.77591 .08333337  8.49  23.06704  .23809522 4.75 19.789913        0 5.08 15.055298 .08333331
2006 10.25  18.32777         0  8.45  22.75918  .08333337 5.35 19.919577        0 4.62  15.00832         0
2007  8.66 17.855055 .08333331  7.66  22.43314 -.14285713 5.26  19.74264        0 4.62 15.214797         0
2008  7.52  18.25556         0  7.06 22.562563          0 5.62 20.502636        0 5.78  15.98871         0
2009  7.74   19.9917         0  8.74 24.080805  .14285713 7.54   22.0684        0 9.25 16.822023         0
2010  6.97  19.56321         0  8.87 23.989256          0 7.79 21.641914        0 9.63 16.743158         0
end