Search code examples
neo4jcypheraverageneo4j-apoc

Compute Avg of list value for each element in Neo4j


The Problem to solve is:

List: [x1, y1, z1], [x2, y2, z2] ...[xn, yn, zn]

Output expected:

[(x1+x2+..+xn)/n, (y1+y2+..yn)/n, (z1+z2+..+z3)/n]

`

I'm able to perform the addition when I've 2 list only and size is fixed using the below statement:

UNWIND(apoc.coll.zip([1,2,3], [4,5,6])) as output

RETURN COLLECT(apoc.coll.avg(output))

Output is

[2.5, 3.5, 4.5]

But wasn't not able to compyte for dynamic number of n list. The size of list is constant for which avg needs to be computed.

Neo4j Desktop Graph version: 3.5.18

APOC LIbrary: 3.5.0.12

Thanks in advance!


Solution

  • Assuming that you pass the list of "sublists" as a parameter, list, this may work for you:

    RETURN [w IN
      REDUCE(s = [], sublist IN $list | CASE
        WHEN SIZE(s) = 0 THEN sublist
        ELSE [i IN RANGE(0, SIZE(s)-1) | s[i] + sublist[i]]
        END) |
      w / TOFLOAT(SIZE($list))] AS result
    

    REDUCE is used to generate a single list with the sums of the corresponding sublist elements.