# Separating positive and negative numbers into two arrays

$c$ is a vector with real numbers.I want to separate the positive ones and the negative ones into two vectors: $a$ and $b$.

I have the following problem: When I do:

c = RandomReal[{-1, 1}, 20];
{a, b} = GatherBy[c, Positive]


Sometimes, $a$ is the one with positive numbers, and some other times $b$ is the one with the positive numbers. Any solution to this problematic randomness?

## 3 Answers

The origin of your problem is that GatherBy gathers your data differently depending on the sign of the first number in list $c$.

You can avoid the problem by sorting the vector of real numbers $c$ before applying GatherBy, so that the $a$ list will always contain negative numbers:

c = Sort[RandomReal[{-1, 1}, 20]];
{a, b} = GatherBy[c, Positive]

• Try it with c = Sort[{-2, -2}]; – Dr. belisarius Mar 7 '13 at 12:47
• @belisarius Yep, in this form it works only under the assumption that the list c contains both positive and negative numbers. – VLC Mar 7 '13 at 13:47

Here's another way that removes the need to sort. Either

 {a, b} = {Select[c, # > 0 &], Select[c, # <= 0 &]}


or

 {a, b} = {Select[c, Positive], Select[c, Negative]}


which do the same thing except for any zero values.

Few more alternatives:

c = RandomReal[{-1, 1}, 10]
(* {-0.672076, -0.572152, -0.298228, -0.386248, 0.604312, -0.185637,
0.983919, -0.926872, 0.479745, 0.407436} *)
{a, b} = Pick[c, Sign@c, #] & /@ {-1, 1} (* or *)
{a, b} = Cases[c, #] & /@ {_?NonPositive, _?Positive} (* or *)
{a, b} = DeleteCases[c, #] & /@ {_?Positive, _?NonPositive} (* or *)
{a, b} = Reap[If[# < 0, Sow[#, neg], Sow[#, pos]] & /@ c, {neg, pos}][]
(* {{-0.672076, -0.572152, -0.298228, -0.386248, -0.185637, -0.926872},
{0.604312, 0.983919, 0.479745, 0.407436}}*)