你如何获得一个随机抽样的10%的总条目的每个独特的员工?
这将用于获得用于审核的随机样本。
发布于 2021-06-28 17:41:17
所以,如果我理解正确的话,你会想得到每名雇员10%的条目作为随机抽样进行审计。那么,在您的情况下,下面的方法应该是好的。
代码:
function getTenPercent() {
var sheet = SpreadsheetApp.getActiveSheet();
// range (including header)
var range = sheet.getRange("A1:C31");
// get values of the range
var values = range.getValues();
// separate header
var headers = values.shift();
// variable to modify where your employee name is stored. 0-indexing
var nameColumn = 0;
// get unique names (excluding blank cells)
var uniqueNames = values.map(row => row[nameColumn]).filter((item, i, ar) => ar.indexOf(item) === i).filter(String);
// in the data we are going to return, already include the header as the first row
var data = [headers];
// for each unique name, we process per name
uniqueNames.forEach(function (name) {
// filter our whole data range containing only the current name
var nameEntries = values.filter(row => row[nameColumn] == name);
// get its length and get the 10% of it
// (using floor so if there are 19 rows, 10% is 1 row)
var entries = nameEntries.length;
var tenth = Math.floor(entries / 10);
// until we get the 10%, loop to get a random row matching the unique name
for(i=0; i<tenth; i++) {
var random = Math.floor(Math.random() * nameEntries.length);
data.push(nameEntries[random]);
// remove the already picked item from the current list to avoid duplicates
nameEntries.splice(random, 1);
}
});
// return data
return data;
}样本输出:

注意:
0作为nameColumn,因为员工名称在我的第一列中。如果您的列在另一列中,请更改它。0-indexing。因此,如果您的列位于第二列,只需减去1并将其存储在变量nameColumn中。如果您的员工姓名在第二栏:var nameColumn = 1;,它应该是这样的。
https://stackoverflow.com/questions/68166182
复制相似问题