0

I am trying to parse data in d3 using the csv function. I am attempting to give each datapoint a new attribute (Region) during processing. Outside the CSV function I defined a function that is supposed to take the datapoint, check to see if the state is Alabama, and if so, assign the Region attribute to a string of either "North" or "South".

var parseRegion = (function(d){
        if(d.State === "Alabama"){
        return "South";
       }
      else {
        return "North";
        }
    });

However, when I run the code, every datapoint is assigned a "Region" attribute that is assigned to the function itself. In other words, it is assigned the actual code, rather than the return values. What am I doing wrong??

d3.csv("data.csv").get(function(error,data){
if (error) throw error;

data.forEach(function(d){
   d.Deaths = +d.Deaths;
   d.Population = +d.Population;
   d.Year = parseDate(d.Year);
   d.Region = parseRegion;
});

Thanks for any help you can provide. Eventually I will add additional states besides Alabama of course.

1 Answer 1

2

Your problem is that you're not calling the parseRegion function that you define.

So you need

 d.Region = parseRegion(d);

More generally d3.csv provides a way to parse the data without the use of forEach. You can do the following:

d3.csv("data.csv")
    .row(function(d) {
    //Code to parse data row by row goes here
    })
    .get(function(error,data){
    //Data is now the whole parsed dataset
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This worked perfectly, and thanks for the clarification on the .row function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.