3
$\begingroup$

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?

$\endgroup$
6
$\begingroup$

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 &]
$\endgroup$
  • $\begingroup$ …obviously, if you don't care about the sign, absolute value is the way to go. :D (+1 of course.) $\endgroup$ – J. M. will be back soon May 11 '15 at 12:24
1
$\begingroup$
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}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.