2015-11-19 67 views
-1

我有如下示例的數據。第一列是id,第二列是v1,第三列是v2。計算平均值並將其轉換爲數據表javascript

數據
var v1Func = d3.random.normal(100, 15) 
var v2Func = d3.random.normal(200, 30) 


    var sample = { 
      id: [], 
      v1: [], 
      v2: [] 

     } 

    for (var i = 0; i < 100; i++) { 
     sample.id.push(i+1); 
     sample.v1.push(v1Func()); 
     sample.v2.push(v2Func()); 
     } 

我的問題是如何計算的平均列V1和V2的,然後轉換數據表是這樣的:

name mean 
v1  * 
v2  * 

提前感謝!

回答

1

我不完全知道你是問什麼,但只要你想它下面讓你與數據的對象:

var v1Func = d3.random.normal(100, 15) 
var v2Func = d3.random.normal(200, 30) 


    var sample = { 
      id: [], 
      v1: [], 
      v2: [], 

     } 

    for (var i = 0; i < 100; i++) { 
     sample.id.push(i+1); 
     sample.v1.push(v1Func()); 
     sample.v2.push(v2Func()); 
     } 

var totalv1 = 0; 
var totalv2 = 0; 
for (var i =0; i < sample.v1.length; i++) { 
    totalv1 += sample.v1[i]; 
    totalv2 += sample.v2[i]; 
} 

var averagev1 = totalv1/sample.v1.length; 
var averagev2 = totalv2/sample.v2.length; 

var dataTable = [ 
    { 
     name: "v1", 
     mean: averagev1 
    }, 
    { 
     name: "v2", 
     mean: averagev2 
    } 
]; 

this snippet.

+0

這正是我想要的!非常感謝! – yxz122930

相關問題