Reputation: 1179
I have got a json file like so:
[
{"id":1,"sex":"Female","programming":5, "project":7},
{"id":2,"sex":"Male","programming":8, "project":4},
{"id":3,"sex":"Female","programming":5, "project":6},
{"id":4,"sex":"Male","programming":4, "project":7}
]
I want to calculate the mean of the value's of programming with D3 js I can get the total mean of it like so:
function meanVak(value) {
return d3.mean(data, function(d) {return d [value] })
}
var meanProgramming = meanVak('programming');
But now i want a separate mean for 'programming' based on sex. So for female and male. How should i do that?
Upvotes: 1
Views: 2832
Reputation: 17940
Seems to me like you need to create a new array that contains only Females/Males and then use the function with the new array, you can create the new array easily using jquery.map().
Look HERE for an example.
var data = [
{"id":1,"sex":"Female","programming":5, "project":7},
{"id":2,"sex":"Male","programming":8, "project":4},
{"id":3,"sex":"Female","programming":5, "project":6},
{"id":4,"sex":"Male","programming":4, "project":7}
];
var newArray = $.map(obj,function(elem){
return elem.sex === 'Female'? elem :null;
});
Upvotes: 0
Reputation: 1273
// I think the easiest way is to use the d3.nest function. Perhaps something like ...
var nest = d3.nest()
.key(function(d) { return d.sex; })
.sortKeys(d3.ascending)
.rollup(function(d) {
return {
meanVakValue: d3.mean(d, function(g) { return g[value]; })
};
})
.map(data);
// You may then need to turn it back into entries. I had to use map first then extract to entries
// but I'm still getting my head around d3.
var nestedData = d3.entries(nest);
Upvotes: 1