I want to create a list of the items in list w tied for appearing the most times in w. In other words, if 22 appears in w more than any other number, I want the result to be {22}. If 34 and 55 appear the most times in w but the same number of times, I want the result to be {34,55}.

The example below just uses a randomly generated list w. My method works but is ugly and inefficient.

w = RandomInteger[100, 200]
fw = w // DeleteDuplicates
wc = Counts[w]
m = Max[fw /. wc]
Reap[Do[If[(fw[[i]] /. wc) == m, Sow[fw[[i]]]], {i, 1, Length[fw]}]][[2, 1]]

Is there a tidier way?


You need Commonest:

w = RandomInteger[100, 200];


{68, 25, 63}

% /. Counts[w]

{5, 5, 5}

| improve this answer | |
  • $\begingroup$ Thank you! The first part is exactly what I need. But you could explain how the syntax of the second part works? I don't even know how to look that up. $\endgroup$ – Jerry Guern Sep 11 '18 at 4:21
  • 1
    $\begingroup$ @JerryGuern, thank you for the accept. About the last line: it gives the same result as {68, 25, 63} /. Counts[w]. % stands for the last result generated . (See Out (%) in the docs.) So the last line is the same as Count[w, #]&/@ {68,25,63}. See also: Map (/@), Function (&) and Slot (#). $\endgroup$ – kglr Sep 11 '18 at 4:38
  • $\begingroup$ Okay, thanks for the followup and links. $\endgroup$ – Jerry Guern Sep 11 '18 at 8:51

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.