0

I am importing a dataset such as this one:

Year,Spain,Rest
2017,"1,688","5,787"
2016,"1,787","5,505"
2015,"1,826","5,187"
2014,"1,822","4,861"

And I need to turn these figures into numbers to display in a D3 graph. I have tried to use this two versions of code to do it but I still get NaN as an answer, so I do not know how to fix this:

d3.csv("stores.csv", function(d, i, columns) {
  for (i = 1, t = 0; i < columns.length; ++i) {
    t += d[columns[i]] = +d[columns[i]];
  }
  d.total = t;
  return d;
}, function(error, data) {
  if (error) throw error;
  console.log(data);
  var keys = data.columns.slice(1);

  data.forEach(function(d) {
    d.Year = parseDate(d.Year);
    d["Spain"]= +(d["Spain"]);
    d["Rest"] = +d["Rest"];
    d["total"] = +d["total"];
    // ...

Instead of + I tried to use parseInt() in this way:

d["Spain"]= parseInt(d["Spain"]);

but it still does not work.

Hope someone can help me with this.

adriaan
  • 1,088
  • 1
  • 12
  • 29
Michael Ro
  • 19
  • 3
  • What is the result of `console.log(d["Spain"])`? Try to expand your questions a bit. One thing though: I don't think you want to use `parseInt(string, radix)` because `parseInt("4,861", 10)` returns `4`. Maybe you need https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat – adriaan Apr 25 '18 at 17:13
  • The result of console.log(d["Spain"]) is NaN. – Michael Ro Apr 25 '18 at 17:15
  • Okay, so it's going wrong before the `forEach`-function. Try to do indenting correctly and use better variable names. That's very helpful for debugging. While you're at it, I would suggest to change your question and code layout so it's more readable by others. Also, do a `console.log(d)` before the line with `d.Year ...` – adriaan Apr 25 '18 at 17:21
  • @epascarello this is not a duplicate I think. Can you unmark it so I can post a solution? Thanks. – adriaan Apr 25 '18 at 17:27

1 Answers1

0

You need to remove , from values before parsing

d["Spain"]= Number(d["Spain"].replace(',', ''));
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • 1
    Thanks! The only other thing I'd mention about your solution is that it assumes commas separate thousands instead of decimals. A little localization knowledge would be helpful here... – Fissure King Apr 25 '18 at 17:07
  • depending on the source of the data `,` may actually mean `.` – Walle Cyril Apr 25 '18 at 17:08
  • Yes, commas are separating thousands instead of decimals. I have tried with this solution but it says: "Typerror: d.Spain.replace is not a function". – Michael Ro Apr 25 '18 at 17:12
  • @MichaelRo Which means you need to look into D3 docs, how to get data. If data is retrieved correctly and only a parsing issue then solution is correct. – Zohaib Ijaz Apr 25 '18 at 17:19