Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Created March 12, 2013 18:15
Show Gist options
  • Save mhawksey/5145411 to your computer and use it in GitHub Desktop.
Save mhawksey/5145411 to your computer and use it in GitHub Desktop.
Generate Sankey data for Google Sheets with this custom formula
function setSankey(data, cols, optSplit) {
// data - is all columns of the the response data minus the header e.g. 'Form Responses'!A2:P
// cols - string of comma seperated column letters
var splitBy = optSplit || ", ";
var output = [["source","target","value"]];
var edges = {};
var cols = cols.split(",");
for (i in cols){
cols[i] = charToCol(cols[i].trim().toUpperCase());
}
for (var c = 0; c < cols.length-1; c++){
for (i in data){
var sources = data[i][cols[c]].split(splitBy);
for (s in sources){
if (sources[s] !=""){
var targets = data[i][cols[c+1]].split(splitBy);
for (t in targets){
if (targets[t] !=""){
if (edges[sources[s]+"|"+targets[t]] == undefined){
edges[sources[s]+"|"+targets[t]] = {source:sources[s],
target: targets[t],
value: 1};
} else {
edges[sources[s]+"|"+targets[t]].value = edges[sources[s]+"|"+targets[t]].value+1;
}
}
}
}
}
}
}
for (i in edges){
output.push([edges[i].source,edges[i].target,edges[i].value]);
}
return output;
}
// http://stackoverflow.com/a/9906193/1027723
function charToCol(val) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;
for (i = 0, j = val.length - 1; i < val.length; i += 1, j -= 1) {
result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1);
}
return result-1;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment