d3.js 如何计算一个属性对另外两个属性的约束条件?

mrfwxfqh  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(96)

这是我的数据:

data = 
   [{ndc_description: "VIAGRA 50 MG TABLET", new_percent_change: 12.9, year: "2017"}, 
    {ndc_description: "VIAGRA 50 MG TABLET", new_percent_change: 12.9, year: "2019"}, 
    {ndc_description: "VIAGRA 50 MG TABLET", new_percent_change: 12.9, year: "2017"}, 
    {ndc_description: "JANUVIA 100 MG TABLET", new_percent_change: 4.41, year: "2017"},
    {ndc_description: "JANUVIA 100 MG TABLET", new_percent_change: 4.41, year: "2019"},
    {ndc_description: "JANUVIA 100 MG TABLET",new_percent_change: 4.41, year: "2017"}]

我如何表示两个ndc_description中的每一个的new_percent_change以及它的相对年份?我想在“year”之后添加另一列,以包含计算值。

更新:我可以计算平均值

roll = d3.rollups(data, v => d3.mean(v, d => d.new_percent_change), d => d.year, d => d.ndc_description)

但我不知道如何将每个值赋给数据数组。

jchrr9hc

jchrr9hc1#

由于roll是一个具有均值的数组数组,因此您可以执行嵌套的forEach循环来查找正确的数据对象,tio您将传递均值:

roll.forEach(yearArray => {
  yearArray[1].forEach(description => {
    const foundObj = data.filter(e => e.year === yearArray[0] && e.ndc_description === description[0]);
    foundObj.forEach(obj => obj.mean = description[1])
  })
});

下面是一个演示,我更改了一些值,以便您可以看到正确的方法:

const data = [{
    ndc_description: "VIAGRA 50 MG TABLET",
    new_percent_change: 10.9,
    year: "2017"
  },
  {
    ndc_description: "VIAGRA 50 MG TABLET",
    new_percent_change: 12.3,
    year: "2019"
  },
  {
    ndc_description: "VIAGRA 50 MG TABLET",
    new_percent_change: 12.9,
    year: "2017"
  },
  {
    ndc_description: "JANUVIA 100 MG TABLET",
    new_percent_change: 8.41,
    year: "2017"
  },
  {
    ndc_description: "JANUVIA 100 MG TABLET",
    new_percent_change: 5.41,
    year: "2019"
  },
  {
    ndc_description: "JANUVIA 100 MG TABLET",
    new_percent_change: 4.41,
    year: "2017"
  }
];

const roll = d3.rollups(data, v => d3.mean(v, d => d.new_percent_change), d => d.year, d => d.ndc_description);

roll.forEach(yearArray => {
  yearArray[1].forEach(description => {
    const foundObj = data.filter(e => e.year === yearArray[0] && e.ndc_description === description[0]);
    foundObj.forEach(obj => obj.mean = description[1])
  })
});

console.log(data)
<script src="https://d3js.org/d3.v7.min.js"></script>

相关问题