Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Stratified Sampling

I have a json data source like this:

var ds=[{"id":1,"group":"A"},{"id":2,"group":"C"},{"id":3,"group":"B"},{"id":4,"group":"A"},{"id":5,"group":"C"},{"id":6,"group":"B"},{"id":7,"group":"A"},{"id":8,"group":"C"},{"id":9,"group":"B"},{"id":10,"group":"A"},{"id":11,"group":"C"}];

Suppose that every group has at least m records(here m=3),I would like to randomly pick n(n<=m) records from each group and merge the samples into a new array like this:

var output=[{"id":1,"group":"A"},{"id":7,"group":"A"},{"id":3,"group":"B"},{"id":6,"group":"B"},{id":2,"group":"C",{"id":11,"group":"C"}]

Any algorithm to do with this case?

like image 955
ken wang Avatar asked Aug 26 '26 16:08

ken wang


1 Answers

Yeah, you can do this pretty cleanly with lodash:

var output = _(ds) //begin chaining syntax
    .groupBy("group") //split into groups
    .map(function(group) { //for each group
        return _.sample(group, n); //sample n items randomly
    })
    .flatten() //flatten array of arrays into a single array
    .value(); //end chaining syntax
like image 130
Retsam Avatar answered Aug 28 '26 05:08

Retsam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!