4
$\begingroup$

How can I alter Commonest so that, when I give it an input of four zeroes and ones such as $\{0,1,1,0\}$, which has an even split in its elements, it returns the first element of the input list, which happens to be $0$ in the example?

$\endgroup$
1
  • 1
    $\begingroup$ Why not just First[Commonest[{0, 1, 1, 0}]]? $\endgroup$
    – user484
    Commented Sep 3, 2014 at 1:14

2 Answers 2

4
$\begingroup$

Use the second argument of Commonest:

Commonest[{0, 1, 1, 0}, 1]
(* {0} *)  

Docs on Commonest>>Details:

Commonest[list,n] returns the n commonest elements in the order they appear in list.

Update: As discovered by m_goldberg (see this answer) and fixed by Mr.Wizard (see this Q/A, Commonest has a bug in Version 10. So, for Version 10, you need to modify kernel.init with Mr.Wizard's fix, or as suggested by @Rahul Narain in the comments, use

 First@Commonest[{0, 1, 1, 0}]

instead of Commonest[{0, 1, 1, 0}, 1].

$\endgroup$
1
  • 1
    $\begingroup$ I get {1} from Commonest[{1, 1, 0, 0}, 1] on V10. $\endgroup$
    – m_goldberg
    Commented Sep 3, 2014 at 0:16
3
$\begingroup$

This is an addendum to kguler's answer.

There is, to me, an inexplicable change in behavior of Commonest between V9 and V10.

data = Permutations[{0, 0, 1, 1}]
{{0, 0, 1, 1}, {0, 1, 0, 1}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 1, 0, 0}}

V9

Commonest[#, 1] & /@ data
{{0}, {0}, {0}, {1}, {1}, {1}}

V10

Commonest[#, 1] & /@ data
{{1}, {1}, {1}, {0}, {0}, {0}}

Therefore, in V10 the first element is never returned as a tie breaker.

$\endgroup$
1
  • $\begingroup$ In fact it seems that in version 10 it is always the last of the equally-common values that is returned. data = Permutations[Riffle[#, #] &@Range[5]]; Position[DeleteDuplicates@#, Commonest[#, 1][[1]]] & /@ data // Union yields {{{5}}}. I think that must be considered a bug. Will you post a Question highlighting this so that we may tag it as such? $\endgroup$
    – Mr.Wizard
    Commented Sep 3, 2014 at 4:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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