【发布时间】:2019-02-23 04:53:35
【问题描述】:
我在Javascript / React 工作,使用一组包含体育数据的对象。
以下是我正在处理的数据示例:
const mydata = [
{ name: "Tom", year: 2018, statA: 23.2, statB: 12.3 },
{ name: "Bob", year: 2018, statA: 13.2, statB: 10.1 },
{ name: "Joe", year: 2018, statA: 18.2, statB: 19.3 },
{ name: "Tim", year: 2018, statA: 21.1, statB: 21.3 },
{ name: "Jim", year: 2018, statA: 12.5, statB: 32.4 },
{ name: "Nik", year: 2017, statA: 23.6, statB: 23.8 },
{ name: "Tre", year: 2017, statA: 37.8, statB: 18.3 },
{ name: "Ton", year: 2017, statA: 15.3, statB: 12.1 },
{ name: "Bil", year: 2017, statA: 32.2, statB: 41.3 },
{ name: "Geo", year: 2017, statA: 21.5, statB: 39.8 }
];
我在这里遇到的数据操作问题感觉非常具有挑战性,我正在苦苦挣扎。我需要按年对数据中的几个键(statA、statB)中的每一个进行缩放(表示 0,stdev 1)。
例如,查看 statA 列中 year === 2018 的值,我们有 [23.2, 13.2, 18.2, 21.1, 12.5]。作为测试,将此向量插入 R 的 scale() 函数会得到以下结果:
scale(c(23.2, 13.2, 18.2, 21.1, 12.5))
[,1]
[1,] 1.1765253
[2,] -0.9395274
[3,] 0.1184989
[4,] 0.7321542
[5,] -1.0876511
attr(,"scaled:center")
[1] 17.64
attr(,"scaled:scale")
[1] 4.72578
...所以在我的原始对象数组中,第一个对象中的值 statA: 23.2 应更新为 1.1765,因为值 23.2 比 Year == 2018 的所有其他 statA 值的平均值高出 1.1765 个标准差. 在我的完整数据集中,我有约 8K 个对象和每个对象中约 50 个键,其中约 40 个我需要逐年扩展。
在高层次上,我认为我必须 (1st) 计算每年每个统计数据的均值和 st dev,并且 (2) 使用该年度该统计数据的均值和 st dev,并将其映射到其标度值。性能/速度对我的应用很重要,我担心普通的 for 循环会非常慢,尽管这是我目前正在尝试的。
对此的任何帮助表示赞赏!
编辑 2:
在我通读/编码之前,想发布我昨天完成的内容:
const scaleCols = ['statA', 'statB'];
const allYears = [...new Set(rawData.map(ps => ps.Year))];
// loop over each year of the data
for(var i = 0; i < allYears.length; i++) {
// compute sums and counts (for mean calc)
thisYearsArray = rawData.filter(d => d.Year === allYears[i])
sums = {}, counts = {};
for(var j = 0; j < thisYearsArray.length; j++) {
for(var k = 0; k < scaleCols.length; k++) {
if(!(scaleCols[k] in sums)) {
sums[scaleCols[k]] = 0;
counts[scaleCols[k]] = 0;
}
sums[scaleCols[k]] += thisYearsArray[j][scaleCols[k]];
counts[scaleCols[k]] += 1;
}
}
console.log('sums', sums)
console.log('counts', counts)
}
...就像我说的不太好。
编辑:使用 d3 的缩放功能会对此有所帮助吗?
【问题讨论】:
-
您要求的是算法而不是此问题的编程解决方案。最好在cs.stackexchange.com/questions/tagged/algorithms 或 math.stackexchamge.com 上提问。您可能还想查看 nodejs 的统计库,例如 stats-lite 以获得一些帮助。
-
although that's what I'm attempting currently.你能发布你目前的尝试是什么让我们看看吗? -
这不是一个真正的算法,而是一个数据操作问题......只是缩放数据
标签: javascript d3.js data-manipulation