Sort a rectangular array of values by values in 1 or 2 rows?

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.
macro
Posts: 70
Joined: Thu Jul 16, 2015 3:01 pm

Sort a rectangular array of values by values in 1 or 2 rows?

Unread post by macro »

I have a rectangular array of integers like this:

Code: Select all

2 2 2 3 3 1 1 0
2 1 3 1 2 3 4 0
and I'd like to sort it by the values in the first row, with ties broken by the values in the second row. Any ties that remain can be "broken" arbitrarily. I'm hoping to avoid implementing my own sort routine for this, but that seems nontrivial because RATS doesn't have any form of stack or linked list data type that can use during the sort. The only strategy I can think of is to cast the rectangular array into a matrix of reals, transpose it, use %sortcl on both columns or some combination of %index calls, then use those indexes on the the original rectangular. Is there a better way to do this?

Using the generic %sort function

Code: Select all

compute v1 = ||2,2,2,3,3,1,1,0|2,1,3,1,2,3,4,0||
display %sort(v1)
returns

Code: Select all

0 0 1 1 1 1 2 2
but I'm not sure how to interpret that output. It seems like it's sorting -v1- without respect to rows or columns, and then truncating the output to the number of columns in -v1-.
TomDoan
Posts: 7814
Joined: Wed Nov 01, 2006 4:36 pm

Re: Sort a rectangular array of values by values in 1 or 2 r

Unread post by TomDoan »

Wouldn't this work:

Code: Select all

dec rect[int] myint(2,8)
input myint
2 2 2 3 3 1 1 0
2 1 3 1 2 3 4 0
dec rect[real] mytrreal(%cols(myint),%rows(myint))
ewise mytrreal(i,j)=myint(j,i)
compute mytrreal=%sortcl(mytrreal,||1,2||)
ewise myint(i,j)=fix(mytrreal(j,i))
macro
Posts: 70
Joined: Thu Jul 16, 2015 3:01 pm

Re: Sort a rectangular array of values by values in 1 or 2 r

Unread post by macro »

That's what I was looking for; thank you.
Post Reply