7
$\begingroup$

I want the in-built function Count to count the elements in a list which are greater than a value.

Example:

Count[{1, 1, 2, 3}, (# > 1.5) &]

Why doesn't this work?

$\endgroup$
7
  • 2
    $\begingroup$ Inverse of (21206); variant of (18054); beware of (1699). $\endgroup$
    – Mr.Wizard
    Oct 20 '14 at 19:05
  • $\begingroup$ @Mr.Wizard Thanksfor the comment. ;) $\endgroup$ Oct 20 '14 at 21:18
  • $\begingroup$ You're welcome. By the way I realize that the close text on this one is a bit dismissive: "simple," "easily," but that is not my intent. I could instead close this as a duplicate of one of the linked questions in the comment above if you would prefer. Also the community may weigh in and decide to reopen it. $\endgroup$
    – Mr.Wizard
    Oct 20 '14 at 21:39
  • 2
    $\begingroup$ @Mr.Wizard I'd vote to open since the function vs. pattern issue is a common mistake for beginner/intermediate MMA users, and I've yet to see a simple Q&A that addresses the issue as this one does. $\endgroup$ Oct 20 '14 at 22:05
  • $\begingroup$ @bobthechemist Did you ever cast a reopen vote? $\endgroup$
    – Mr.Wizard
    Oct 30 '14 at 9:26
12
$\begingroup$

Your second argument is a function instead of a pattern.

Count[{1, 1, 2, 3}, _?(# > 1.5 &)]
$\endgroup$
8
  • $\begingroup$ Ups... Many thanks ;) $\endgroup$ Oct 20 '14 at 18:26
  • $\begingroup$ @Fred Simons Dear Fred, could you please kindly comment the following. The function Select is quite close to Count by its functionality. However, it recognizes the pattern argument in the form given in the above question, that is, just #>1.5& as follows: Select[{1, 1, 2, 3}, (# > 1.5 &)] returns {2, 3}. What is the difference between these two cases? $\endgroup$ Feb 9 '16 at 9:34
  • $\begingroup$ Check Mr. Wizard's comment to the OP. Specifically the first link. $\endgroup$
    – Emy
    Feb 9 '16 at 9:38
  • $\begingroup$ @AlexeiBoulbitch please see (88220) $\endgroup$
    – Mr.Wizard
    Feb 9 '16 at 11:56
  • $\begingroup$ Dear @Alexei. I was out for some days, so I am a bit late in replying. In the mean time you have already got the link to Mr. Wizard's answer. I can only add that for me, Select and Count are not not so close, still apart from the fact that the first one uses a criterion function and the second one a pattern. Count can be used on any level: Count[{{1,2},3,4}, _Integer, 2]. This cannot be done with Select, that works only on level 1. $\endgroup$ Feb 10 '16 at 9:18
5
$\begingroup$

In V10.0+ you can stick with functions:

CountsBy[{1, 1, 2, 3}, (# > 1.5) &][True]
$\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.