[英]Calculate moving average by group/column - javascript
I have a function that calculates an moving average. 我有一个计算移动平均值的函数。 In the array i'm using there is a group variable (department) that in the present function are blurred together. 在我正在使用的数组中,有一个组变量(部门)在当前函数中被模糊在一起。 I would like to do the ma-calculations by group instead. 我想按组进行ma计算。 Is that even possible( elegantly , I might add. I could probably brute force it with my beginner-knowledge...)? 甚至有可能( 优雅地 ,我可能会补充。我可能会以我的初学者知识来蛮力……)? I do some filtering later on (by department) but I would like to have the calculations done once and then be done with it. 稍后(按部门)我会进行一些过滤,但是我想先进行一次计算,然后再进行计算。
Do anyone have an elegant solution? 有人有一个优雅的解决方案吗? If there is a better way to do this than using map it's ok as well. 如果有比使用map更好的方法,那么也可以。
var movingWindowAvg = function (arr, step) { // ma size = step
return arr.map(function (_, idx) {
var wnd = arr.slice(idx, idx + step);
var result = d3.sum(wnd.map(function(d) { return d.cases; })) / wnd.length; if (isNaN(result)) { result = _; };
var nBeds= d3.sum(wnd.map(function(d) { return d.Beds; })) / wnd.length; if (isNaN(platser)) { platser = _; };
var avd = wnd[0].Department;
if (wnd.length < step) {
console.log(wnd)
}
var tmpDate = wnd[wnd.length-1].datum; //Test to get the date-markers correct
return {Cases: result, Date: tmpDate, Beds: nBeds, Department: avd, };
});
};
In the end I didn't find any good way to do this by group and it might be beneficial to have the un-edited values in the original ds (for example if I would like to make it possible to toggle ma or not) 最后,我找不到按组进行此操作的任何好方法,并且在原始ds中包含未编辑的值可能会有所益处(例如,如果我想使是否切换为ma成为可能)
This is the final code, i use slice to remove undefined objects afterwards: 这是最终的代码,之后我使用slice删除未定义的对象:
var movingWindowAvg = function (arr, step) { // Window size = step
return arr.map(function (_, idx) {
var wnd = arr.slice(idx, idx + step);
counter = Object_size(wnd);
if (counter == step) {
var result = d3.sum(wnd.map(function(d) { return d.persons; })) / wnd.length; if (isNaN(result)) { result = _; };
var nbeds= d3.sum(wnd.map(function(d) { return d.beds; })) / wnd.length; if (isNaN(nbeds)) { nbeds= _; };
var tmpavd = wnd[0].Dep;
var tmpDate = wnd[step-1].datum;
return {Persons: result, date: tmpDate, Beds: nbeds, Department: tmpavd , };
}
});
Update, the Object_size function as well: 更新Object_size函数:
Object_size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
} return size;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.