Arun GK
Arun GK

Reputation: 85

Compare data element with partial mean in d3

I have the following data

 [{"devcount" : 1  , "dayofweek" :0, "hour" : 1  },
  {"devcount" : 2  , "dayofweek" :0, "hour" : 2  },

  {"devcount" : 3  , "dayofweek" :1, "hour" : 2  },
  {"devcount" : 4  , "dayofweek" :1, "hour" : 3  },
  {"devcount" : 6  , "dayofweek" :1, "hour" : 4  },
  {"devcount" : 5  , "dayofweek" :1, "hour" : 5  },

  {"devcount" : 7  , "dayofweek" :2, "hour" : 5  },
  {"devcount" : 8  , "dayofweek" :2, "hour" : 6  },
  {"devcount" : 9  , "dayofweek" :2, "hour" : 7  },
  {"devcount" : 10 , "dayofweek" :2, "hour" : 9  }]

It is required to compare the devcount with the group average of devcount for each dayofweek. i.e. for the fist row, devcount=1 is to be compared with the the average device count for the dayofweek-0 (= 1.5) and "yes" to be returned if the devcount is lesser. Else "No" should be returned.

I have coded as below.

smry=d3.nest()
.key( function(d) { return d.dayofweek;}) 
.rollup(function(d) {return d3.mean(d, function(g) {return g.devcount; })})        
.entries(result);

I am not sure how to compare the smry data and the original data. The original data will be used in selectAll for creating rectangles and the output after comparison needs for determining the colour of the rectangle

Upvotes: 0

Views: 78

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can do it as shown in the snippet below.

 test = [{
     "devcount": 1,
     "dayofweek": 0,
     "hour": 1
   }, {
     "devcount": 2,
     "dayofweek": 0,
     "hour": 2
   },

   {
     "devcount": 3,
     "dayofweek": 1,
     "hour": 2
   }, {
     "devcount": 4,
     "dayofweek": 1,
     "hour": 3
   }, {
     "devcount": 6,
     "dayofweek": 1,
     "hour": 4
   }, {
     "devcount": 5,
     "dayofweek": 1,
     "hour": 5
   },

   {
     "devcount": 7,
     "dayofweek": 2,
     "hour": 5
   }, {
     "devcount": 8,
     "dayofweek": 2,
     "hour": 6
   }, {
     "devcount": 9,
     "dayofweek": 2,
     "hour": 7
   }, {
     "devcount": 10,
     "dayofweek": 2,
     "hour": 9
   }
 ];

 //make the summary using nest
 smry = d3.nest()
   .key(function(d) {
     return d.dayofweek;
   })
   .rollup(function(d) {
     return d3.mean(d, function(g) {
       return g.devcount;
     })
   })
   .entries(test);
test.forEach(function(t) {
    //find the value from summary for dayofweek
    var k = smry.find(function(s) {
        return (s.key == t.dayofweek)
    }); 
    //check the day of week with the mean, set the flag in the data
    if(k.values<t.devcount){
      t.flag = true;
    } else {
        t.flag = false;
    }
});

console.log(test);//this now has the flag to determine the color
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 1

Related Questions