Crossfilter and DC.js: reduce to unique number
在下面的示例中,我试图通过
这是我的数据:
1 2 3 4 5 6 7 | {"Respond_Id":258,"Gender":"Female","Age":"18-21","Answer":424}, {"Respond_Id":258,"Gender":"Female","Age":"18-21","Answer":428}, {"Respond_Id":261,"Gender":"Male","Age":"22-26","Answer":427}, {"Respond_Id":261,"Gender":"Male","Age":"22-26", "Answer":432}, {"Respond_Id":345,"Gender":"Female","Age":"27-30","Answer":424}, {"Respond_Id":345,"Gender":"Female","Age":"27-30","Answer":425}, {"Respond_Id":345,"Gender":"Female","Age":"27-30","Answer":433}, |
我知道我应该为此使用 group reduce,所以我尝试了(改编自示例):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var ntotal = answerDim.group().reduce( function(p, d) { if(d.Respond_Id in p.Respond_Ids){ p.Respond_Ids[d.Respond_Id]++; } else { p.Respond_Ids[d.Respond_Id] = 1; p.RespondCount++; } return p; }, function (p, d) { p.Respond_Ids[d.Respond_Id]--; if(p.Respond_Ids[d.Respond_Id] === 0){ delete p.Respond_Ids[d.Respond_Id]; p.RespondCount--; } return p; }, function () { return { RespondCount: 0, Respond_Ids: {} }; } ); |
然后:
1 2 3 4 5 | numberDisplay .group(ntotal) .valueAccessor(function(d){ return d.value.RespondCount; }); dc.renderAll(); |
但似乎不起作用。有人知道如何使它工作吗?谢谢
根据您的 JSFiddle,您的设置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | var RespondDim = ndx.dimension(function (d) { return d.Respond_Id;}); var ntotal = RespondDim.group().reduce( function(p, d) { if(d.Respond_Id in p.Respond_Ids){ p.Respond_Ids[d.Respond_Id]++; } else { p.Respond_Ids[d.Respond_Id] = 1; p.RespondCount++; } return p; }, function (p, d) { p.Respond_Ids[d.Respond_Id]--; if(p.Respond_Ids[d.Respond_Id] === 0){ delete p.Respond_Ids[d.Respond_Id]; p.RespondCount--; } return p; }, function () { return { RespondCount: 0, Respond_Ids: {} }; }); |
这里需要注意的重要一点是,默认情况下,您的组键与维度键相同。因此,每个受访者 ID 将有一组。这不是你想要的。
您可以切换到使用专为此用例设计的
1 | var RespondDim = ndx.dimension(function (d) { return true;}); |
现在你会看到
1 | {key: true, value: {RespondCount: 3, Respond_Ids: {258: 2, 261: 2, 345: 3}}} |
工作小提琴:https://jsfiddle.net/v0rdoyrt/2/