J86
J86

Reputation: 15237

Single Crossfilter Dimension and Group on two columns?

I have the following CSV:

ccgcode,ccgname,metric,male,female
06M,Great Yarmouth And Waveney,3,24,76
05G,North Staffordshire,3,46,54
... etc.

How do I get about creating a Sex dimension to drive a dc.pieChart()? My question is specifically about the Dimension and Group aspect of Crossfilter, and not how to render the pie chart.

Upvotes: 0

Views: 818

Answers (1)

John William Domingo
John William Domingo

Reputation: 487

Crossfilter can't simply sum up the two columns you need so reformatting the data is your best bet (as per the conversation in the comments). You can use melt.js, which works like reshape if you're familiar with R, so you don't have touch your raw data.

This solution assumes your data is a list of objects with key-value pairs (pretty standard):

data = [
  { ccgcode: '06M', ccgname: 'Great Yarmouth And Waveney', metric: 3, male: 24, female: 76 },
  { ccgcode: '05G', ccgname: 'North Staffordshire', metric: 3, male: 46, female: 54 },
...];

You first want to identify all the static columns you don't want to "melt" (disaggregate):

var staticColumns = ['ccgcode', 'ccgname', 'metric'];

Then you use melt to ungroup male and female columns. Melt takes in your data, the columns you don't want to melt, and the name of the new melt column (in your case it's sex):

var ndx = crossfilter(melt(data, staticColumns, 'sex', 'count'));
var sexDim  = ndx.dimension(function (d) { return d.sex; });

You end up with the following dimension:

sexDim = [
  { sex: 'male', count: 24, _id: 0, ccgcode: '06M', ccgname: 'Great Yarmouth And Waveney', metric: 3 },
  { sex: 'male', count: 46, _id: 1, ccgcode: '05G', ccgname: 'North Staffordshire', metric: 3},
  { sex: 'female', count: 76, _id: 0, ccgcode: '06M', ccgname: 'Great Yarmouth And Waveney', metric: 3 },
  { sex: 'female', count: 54, _id: 1, ccgcode: '05G', ccgname: 'North Staffordshire', metric: 3},
...];

Note the helpful _id that melt creates for you in case you need to tie everything back together (although your static columns help with this too). You can pass false as the fifth parameter to melt to exclude the _id property.

And you can still group by sex:

var males = sexDim.group().reduceSum(function (d) {
  if (d.sex === 'male') {
    return d.count;
  } else {
    return 0;
  }
});

Hope that helps!

Upvotes: 2

Related Questions