0

我对 javascript 或 D3.js 不是很有经验,需要一些指导。

我有两个想要加入的数据集(对象数组)。我正在尝试通过“加入”答案将全国平均分数与州平均分数对齐。要浏览数据,您可以将其剪切并粘贴到Tributary中。

// National Averages Dataset
var nationaldataset = [];
var nAvg = "http://data.medicare.gov/resource/89u8-shx4.csv"; 
var nscore = "HCAHPS Answer Percent";
var nquestion = "HCAHPS Question";
var nanswer = "HCAHPS Answer Description";

d3.csv( nAvg, function(data)  {
    nationaldataset = data.map(function(d) { return [ d[nquestion], d[nanswer], d[nscore] ]; });
    d3.select("body").selectAll("p")
        .data(nationaldataset)
        .enter()
        .append("p")
        .text( function(d) {return d ;} );  

});
// State Averages Dataset
var statedataset = [];
var sAvg = "http://data.medicare.gov/resource/fhk8-g4vc.csv"; //State Average
var sq1 = "Percent of patients who reported that their nurses \"Sometimes\" or \"Never\" communicated well."
var sq2 = "Percent of patients who reported that their nurses \"Usually\" communicated well."
var sq3 = "Percent of patients who reported that their nurses \"Always\" communicated well."
// .. this list goes on for 30 columns
d3.csv( sAvg, function(data) {
    sstatedataset = data.map(function(d) { return [ d["State"], d[sq1], d[sq2], d[sq3] ]; });
    d3.select("body").selectAll("p")
        .data(statedataset)
        .enter()
        .append("p")
        .text(function(d) {return d ;} );

});

我查看了几种 javascript 数组处理方法(Join()、Concatenate() 等),但都画了一个空白。我将如何去做这样的事情 -

Select nationaldataset.nquestion
, nationaldataset.nanswer
, nationaldataset.nscore
, statedataset.Score
From nationaldataset, statedataset 
WHERE nationaldatset.nanswer = statedataset.columnname 
AND statedataset.State in ['SD', 'MN', 'IA'] 
4

1 回答 1

1

不幸的是,Javascript 中没有join运算符或等效项——您必须明确搜索匹配项。在您的情况下,您可以使用嵌套循环来执行此操作。代码看起来像这样。

var results = [];
for(var i = 0; i < statedataset.length; i++) {
  if(statedataset[i].State == "SD" ||
     statedataset[i].State == "MN" ||
     statedataset[i].State == "IA") {
    var j = 0;
    for(j = 0; j < nationaldataset.length; j++) {
      if(nationaldataset[j].nanswer == statedataset[i].columnname) {
        break;
      }
    }
    if(j < nationaldataset.length) {
      results.push({
        "nquestion": nationaldataset[j].nquestion,
        "nanswer": nationaldataset[j].nanswer,
        "nscore": nationaldataset[j].nscore,
        "Score": statedataset[i].Score
      });
    }
  }
}

这应该为您提供一个可以与 D3 一起使用的数据结构。是的,几乎可以肯定有更好的方法来做到这一点。

于 2013-08-22T19:19:18.830 回答