excellambda

Using Excel Lambda function to count numbers that meet a condition (in conjunction with groupby)


I am trying to write a lambda function for use in a groupby, which counts the total number of failed grades (grades below 6) for each store. However I cannot seem to figure it out.

It seems that there are two issues:

  1. Excel treats empty cells as zero (i.e. =A1<6 evaluates to true if A1 is empty)
  2. I can not get the order of operations correct. I need to first check whether a cell is below 6, and only then take the count.

This is my input data:

Store Grade
North 8
South
City 6
Station 6
North 4
City 3
City 5

Expected output:

Store Number of grades <6
North 1
South 0
City 2
Station 0

The simplest lambda I can think of is this:

=LAMBDA(x; COUNTIF(x; "<6"))

But this gives me value errors when used in conjunction with GROUPBY. My GROUPBY statement looks like this:

=GROUPBY(A2:A8;B2:B8; LAMBDA(x; COUNTIF(x; "<6")))

When testing the lambda separately it works just fine, and returns a single number when applied to a range.

I have also tried a nested lambda that works when I test it separately, but also gives value errors when combined with GROUPBY.

=LAMBDA(y; SUM(LAMBDA(x; COUNTIF(x; "<6"))(y)))

I also tried a whole bunch of variants with regular IF statements, such as:

=LAMBDA(x; SUM(IF(x<6; 1; 0)))

Which do evaluate but give the wrong results since my data contains empty cells and those are treated as being <6.

Adding more complex constructions with AND and NOT and ISBLANK do not seem to work since they give me some unexpected behaviour when working with arrays instead of single numbers.


Solution

  • Just add a condition to exclude the blanks, you had the rest already there:

    =GROUPBY(A2:A8, B2:B8, LAMBDA(g, SUM((g<6)*(g<>""))))
    

    or SUMPRODUCT for no reason:

    =GROUPBY(A2:A8,B2:B8, LAMBDA(g, SUMPRODUCT((g<6)*(g<>""))))
    

    or ISNUMBER equivalent:

    =GROUPBY(A2:A8, B2:B8, LAMBDA(g, SUM(--(ISNUMBER(g)*(g<6)))))