1

我有一个像这样的json文件:

[
 {"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} 
]

我想计算使用 D3 js 编程的值的平均值,我可以得到它的总平均值,如下所示:

function meanVak(value) {
    return d3.mean(data, function(d) {return d [value] })
}

var meanProgramming = meanVak('programming');

但是现在我想要一个基于性别的“编程”的单独平均值。所以对于女性和男性。我该怎么做?

4

2 回答 2

1
// 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);
于 2012-11-27T14:40:24.653 回答
0

在我看来,您需要创建一个仅包含女性/男性的新数组,然后将该函数与新数组一起使用,您可以使用jquery.map()轻松创建新数组。

这里的例子。

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;
});
于 2012-11-27T14:42:17.920 回答