Solved
Contributor
Posts: 28

# problem of sorting

I have a data file where one of the variables has a value of -1 0 1

for example,
a
1
1
1
1
1
-1
-1
-1
-1
0
0
0

a
1
-1
1
-1
1
-1
1
-1
1
0
0
0

Accepted Solutions
Solution
‎03-05-2015 05:12 AM
SAS Employee
Posts: 340

## Re: problem of sorting

You want reorder your dataset so that first 1s and -1s come alternately, and at the end all the 0s ?

data want;

do until(eof1 and eof_1);

if not eof1 then do;

set have(where=(a=1)) end=eof1;

output;

end;

if not eof_1 then do;

set have(where=(a=-1)) end=eof_1;

output;

end;

end;

do until(eof0);

set have(where=(a=0)) end=eof0;

output;

end;

stop;

run;

All Replies
Super User
Posts: 9,599

## Re: problem of sorting

You would need to manually put something in your data to sort like that as there's no "logical" sort order.  Why do you want the negatives interleaved with the 1s, is that because of other variables?  If so include those variables in the sort.

Solution
‎03-05-2015 05:12 AM
SAS Employee
Posts: 340

## Re: problem of sorting

You want reorder your dataset so that first 1s and -1s come alternately, and at the end all the 0s ?

data want;

do until(eof1 and eof_1);

if not eof1 then do;

set have(where=(a=1)) end=eof1;

output;

end;

if not eof_1 then do;

set have(where=(a=-1)) end=eof_1;

output;

end;

end;

do until(eof0);

set have(where=(a=0)) end=eof0;

output;

end;

stop;

run;

Contributor
Posts: 28

## Re: problem of sorting

perfect solution
I have one more question if you can do it this way

1

1

-1

-1

1

1

-1

-1

0

0

0

0

or

1

1

1

1

-1

-1

-1

-1

1

1

1

1

-1

-1

-1

-1

0

0

0

0

and so on

SAS Employee
Posts: 340

## Re: problem of sorting

Is this a homework?

data want;

numConsec=2;/*set this to 1, 2 or 4 ...*/

do until(eof1 and eof_1);

do i=1 to numConsec;

if not eof1 then do;

set have(where=(a=1)) end=eof1;

output;

end;

end;

do i=1 to numConsec;

if not eof_1 then do;

set have(where=(a=-1)) end=eof_1;

output;

end;

end;

end;

do until(eof0);

set have(where=(a=0)) end=eof0;

output;

end;

stop;

run;

not tested!

Contributor
Posts: 37

## Re: problem of sorting

If am not wrong, you want to interleave -1s between 1s . Let's add one more variable , assign consecutive odd numbers to -1s and even numbers to 1s and sort using that variable

data

have

;

input a ;

cards;

1

1

1

1

1

-1

-1

-1

-1

0

0

0

;

run;

data

want(drop = odd even )

;

set

have

;

retain odd 1 even 2;

if a = 1 then do;

odd = odd + 2;

sort_var = odd;

output;

end;

else if a = -1 then do;

even = even +2 ;

sort_var = even;

output;

end;

else do;

sort_var = 1000000;

output ;

end;

run;

proc sort data = want; by sort_var;run;

proc print data = want ;run;

🔒 This topic is solved and locked.