Sort strings based on certain values

Use this forum to post questions about syntax problems or general programming issues. Questions on implementing a particular aspect of econometrics should go in "Econometrics Issues" below.

Sort strings based on certain values

Unread postby varcabic » Mon Oct 25, 2021 4:55 am

Hi all,

I have a seemingly simple problem I cannot solve.

I have a list of countries such as this one:
Code: Select all
declare vector[string] labels
compute labels = ||"AT", "BE", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HR", "HU", "IE", "IT", "LT", "LU", "LV" ,"NL", "PL", "PT", "RO", "SE", "SI", "SK", "UK"||


I would like to sort these strings according to certain values. These values could be a series or a vector[real]. However, I cannot put labels into series and use order instruction. Also, I cannot merge strings with real numbers into an array and use %rankc function.

All I managed to do is rank them in the report, such as this one:

Code: Select all
report(action=define,title="Business cycle synchronization in the EU based on synchronicity measure",hlabels=||"","Full sample","","","Post 2007 sample","",""||)
report(atrow=1,atcol=1) "Country" "HP gap" "Average gap" "PC coherent gap" "HP gap" "Average gap" "PC coherent gap"
do i = 1,size
   compute [label] hp  = "sync_hp_"+labels(i)
   compute [label] avg = "sync_avg_"+labels(i)
   compute [label] opt = "sync_opt_"+labels(i)
   *
   sstats(mean) / %s(hp)>>s_hp %s(avg)>>s_avg %s(opt)>>s_opt
   sstats(mean) substart * %s(hp)>>s_hp07 %s(avg)>>s_avg07 %s(opt)>>s_opt07
   
   report(atrow=i+1,atcol=1) labels(i) s_hp s_avg s_opt s_hp07 s_avg07 s_opt07
end do i
report(action=format,picture="*.###")
report(action=sort,bycol=4,atrow=2)
report(action=show,window="synchronicity")


I would like to sort labels(i) according to s_opt value.

Thanks in advance,

Vladimir
varcabic
 
Posts: 5
Joined: Thu Oct 10, 2013 5:34 am

Re: Sort strings based on certain values

Unread postby TomDoan » Thu Nov 04, 2021 1:20 pm

If I understand correctly, you want to do something like this:

Code: Select all
declare vector[string] labels
compute labels = ||"AT", "BE", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HR", "HU", "IE", "IT", "LT", "LU", "LV" ,"NL", "PL", "PT", "RO", "SE", "SI", "SK", "UK"||
dec vect[real] values(%size(labels))
compute values=%ran(1.0)
compute sortix=%index(values)
declare vector[string] reordered(%size(labels))
ewise reordered(i)=labels(sortix(i))


The %INDEX function gives you to (smallest to largest) sort index for a VECTOR. (If you want largest to smallest, use %index(-1.0*values)) and you use that to rearrange the strings.
TomDoan
 
Posts: 7231
Joined: Wed Nov 01, 2006 5:36 pm


Return to Help With Programming

Who is online

Users browsing this forum: No registered users and 1 guest