dc.js - how to get the average of a column in data set

crossfilter, d3.js, dc.js, javascript

Solution

You need to use the group.reduce(add, remove, initial) method, like:

var col1DimTotal = col1Dim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

function reduceAdd(p, v) {
  ++p.count;
  p.total += v.value;
  return p;
}

function reduceRemove(p, v) {
  --p.count;
  p.total -= v.value;
  return p;
}

function reduceInitial() {
  return {count: 0, total: 0};
}

Because you're using dc.js, you'll need to use chart.valueAccessor method to use the average in your charts, like:

chart.valueAccessor(function(p) { return p.value.count > 0 ? p.value.total / p.value.count : 0; });

Problem

I have this below data. ``` col1 col2 value a 01/01/14 10 a 01/01/14 35 a 01/01/14 68 a 01/01/14 21 a 01/01/14 24 b 01/01/14 26 b 01/01/14 35 b 01/01/14 39 b 01/01/14 87 c 01/01/14 25 c 01/01/14 63 c 01/01/14 11 c 01/01/14 25 c 01/01/14 35 ``` If I wanted to take the sum of col1. I could do it by using `col1Dim.group().reduceSum(function(d) { return d.value })`. If I need the count i can replace sum with count. But I'm here loooking for average. So to that. I need to take sum of col1 and count of col1. Any idea how can i divide and get the average? Please help. Stuck in this for almost 3 days.

Original source