# How can Tally group elements that differ only by a sign together?

I have a list

{{1,-2},{2,2},{-1,2},...}


and I want to use Tally to count how often a given pattern appears in the list. This works perfectly, but in addition I want to count elements that differ only by a sign together. This means in the example above it should tell me that I have

{1,-2} two times and

{2,2} one time.

How can this be done?

You can add second argument wrt comparison test. Depending on what your sameness test is e.g (1,-2) same as (-1,2) but not (1,2) or (-1,-2) then:

Tally[test, #1 == #2 || #1 == -#2 &]


or if (1,-2) same as (-1,2) same as (1, 2) same as (-1,-2):

Tally[test, Abs@#1 == Abs@#2 &]

• …obviously, if you don't care about the sign, absolute value is the way to go. :D (+1 of course.) Commented May 11, 2015 at 12:24
test = {{1, -2}, {2, 2}, {-1, 2}, {3, 3}};
{#[[1]], Length@#} & /@ GatherBy[test, Abs]


{{{1, -2}, 2}, {{2, 2}, 1}, {{3, 3}, 1}}

Values @ GroupBy[test, Abs, {First @ #, Length @ #} &]


{{{1, -2}, 2}, {{2, 2}, 1}, {{3, 3}, 1}}

Tally[Abs @ test] /. Thread[Abs @ test -> test]


{{{1, -2}, 2}, {{2, 2}, 1}, {{3, 3}, 1}}