mikael-s
mikael-s

Reputation: 322

Conditionally counting elements in a column in an org-mode spreadsheet

I'm using emacs-calc through org-mode spreadsheet and I would like to count the number of values, in a column, that are greater than a specific value (say 10).

I'm currently using emacs-calc for the computations, but if there is a solution in emacs-lisp, it would be very welcome!

I know that vcount would count the number of values in a vector, but that would count all the values in that vector. How could I add a condition so that only values > 10 are counted?

In other words, I would like a mysterious_function that would return 2 in such a case:

mysterious_function([2,14,11,3,9,1])

Upvotes: 6

Views: 2079

Answers (4)

mikael-s
mikael-s

Reputation: 322

I found a solution, using emacs-calc, inspired by choroba's proposal.

vcount(map(<if(gt(#1,10), 1, [])>, [15,2,5,13]))

So, for treating a column in org-mode spreadsheet, I can do, for example:

vcount(map(<if(gt(#1,10), 1, [])>, @I..@II))

The map function is used to apply a function (an anonymous one, in that case) to each element of a vector. If the element is greater than 10, we put a 1, otherwise an empty vector.

Upvotes: 5

Yann Vernier
Yann Vernier

Reputation: 15887

Since the logical operations produce 1 for true and 0 for false, we can simply sum the test:

vsum(map(<gt(#1,10)>,@I..@II))

Upvotes: 4

choroba
choroba

Reputation: 242228

You can also create an additional column that will contain

if($2>10,1,string(""))

And then simply apply vcount on this column.

Upvotes: 4

Luke Girvin
Luke Girvin

Reputation: 13452

How could I add a condition so that only values > 10 are counted?

In other words, I would like a mysterious_function that would return 2 in such a case:

mysterious_function([2,14,10,3,9,1])

Er, you only have one value greater than 10 in that list - do you mean >= 10?

Anyway, I don't know about org-mode spreadsheets, but here is how to do it in Emacs Lisp:

(defun mysterious-function (vector)
  (length
   (remove-if-not #'(lambda (n)
              (>= n 10))
          (append vector nil))))

Upvotes: 5

Related Questions