Built with blockbuilder.org
Created
December 9, 2015 13:16
-
-
Save quizzicol/39e68c6b2bc8b2e9b25a to your computer and use it in GitHub Desktop.
ParseCSV example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> | |
<meta name="description" content="Parse CSV"> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
</body> | |
<script> | |
// from https://www.youtube.com/watch?v=iuA-gmvJ5n0&list=PL9yYRbwpkyktAZaphR2UfeYpgNGnIqjs9&index=10 | |
function parseCSV(string, accessor) { | |
if (!accessor) { | |
accessor = function(d) { return d }; | |
}; | |
var lines = string.split("\n"), | |
columnNames = lines[0].split(","), | |
rows = lines.slice(1); | |
return rows.map(function(row) { | |
var entries = row.split(","), | |
rowObject = {}; | |
columnNames.forEach(function(colName, i) { | |
rowObject[colName] = entries[i]; | |
}); | |
return accessor(rowObject); | |
}); | |
} | |
iris_data = "sepal_length,sepal_width,petal_length,petal_width,class\n\ | |
5.1,3.5,1.4,0.2,Iris-setosa\n\ | |
4.9,3.0,1.4,0.2,Iris-setosa\n\ | |
4.7,3.2,1.3,0.2,Iris-setosa\n\ | |
4.6,3.1,1.5,0.2,Iris-setosa\n\ | |
5.0,3.6,1.4,0.2,Iris-setosa\n\ | |
5.4,3.9,1.7,0.4,Iris-setosa;" | |
data = parseCSV(iris_data, function(rowObject) { | |
rowObject["sepal_length"] = +rowObject["sepal_length"]; | |
rowObject["sepal_width"] = +rowObject["sepal_width"]; | |
rowObject["petal_length"] = +rowObject["petal_length"]; | |
rowObject["petal_width"] = +rowObject["petal_width"]; | |
return rowObject; | |
}) | |
d3Data = d3.csv.parse(iris_data) | |
console.log(data) | |
console.log("---------D3-----------") | |
console.log(d3Data) | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment