我正在阅读一个csv文件,需要使用D3.js或普通JavaScript从这些数据中计算两个数字:
这可能只需一步即可完成,但我为了解释的目的将其分解:
读入数据后,我需要遍历每一列,标记为“一”到“十” (这些数据的长度是未知长度,因此最多可能达到12或20),
...每次将“乘数”之后的每一列乘以称为“乘数”的变量 (在数据中,我给它任意值1.5,1,0,5,使阅读视觉更清晰)。
这给出了一个新的数字网格,从中可以计算出从1到n的每个ID的每个新数字的最高得分和最低得分。因此每个ID都有最大值和最小值。我需要知道作为变量返回的整个数据中这些新分数的最大值和最小值。
读入数据:
d3.csv("data.csv", function(csv) {
var mydata = bars
.selectAll("rect")
.data(csv)
.enter()
};
示例数据显示为:
ID,总,mutiplier,一个,两个,三个,四个,五个,六个,七个,八个,九个,十个 1,16500,1.5,0.362,0.37,0.1,0.101,0.035,0.362,0.37,0.1,0.101,0.035 2,61000,1,0.426,0.382,0.115,0.084,0.053,0.426,0.382,0.115,0.084,0.053 3,48700,1.5,0.156,0.531,0.195,0.399,0.14,0.156,0.149,0.106,0.399,0.14 4,33000,0.5,0.462,0.409,0.149,0.106,0.149,0.106,0.085,0.1,0.106,0.051 5,8000,0.5,0.327,0.316,0.085,0.1,0.085,0.1,0.057,0.245,0.1,0.057 6,12760,1,0.149,0.195,0.057,0.245,0.057,0.245,0.119,0.114,0.245,0.08
此原始数据无法替换,因为我稍后会引用它。
所以根据这些数据,在遍历所有列之后,从每个列中获取最大值和最小值 - 最小值为0.003535,最大值为3.8875575
...我需要函数返回var min和var max以进行下一次计算。
希望有人可以提供帮助!
答案 0 :(得分:0)
您可以将数据作为文本加载的一种方法,后者使用d3.csv.parseRows
将CSV解析为数组数组。所以只需要切片,忽略前3列。
d3.text('data.csv', function(text)
{
var rows = d3.csv.parseRows(text, function(row, index)
{
// skip header, coerce to Number values
if(index > 0)
{
return row.map(Number);
}
});
var extent = rows.reduce(function(result, row)
{
return d3.extent(result.concat(row.slice(3).map(function(value)
{
return value * row[2];
})));
}, [NaN, NaN]);
var min = extent[0];
var max = extent[1];
});
其他方式如果对象数组是更方便的结构以供以后绘图,您可以执行以下操作。
var nonMeasureColumns = {'ID': 0, 'total': 0, 'multiplier': 0};
d3.csv('data.csv')
.row(function(row)
{
for(var key in row)
{
row[key] = Number(row[key]);
}
return row;
})
.get(function(error, rows)
{
var extent = rows.reduce(function(result, row)
{
return d3.extent(result.concat(d3.map(row).entries()
.filter(function(entry)
{
return !(entry.key in nonMeasureColumns);
})
.map(function(entry)
{
return entry.value * row['multiplier'];
})
));
}, [NaN, NaN]);
var min = extent[0];
var max = extent[1];
});