Jeremy G
Jeremy G

Reputation: 2409

d3 modifying column names

I have a tsv file that I am parsing using the following code:

d3.tsv(file, function(error, data) {
    data.forEach(function(d) {
        d.NAME = d.NAME;
        d.logFC = d.logFC;
        d.logCPM = d.logCPM;
        d.FDR = d.FDR;
        d.PValue = d.PValue
    });

I am trying to account for cases where the user does not input a file with exactly the same column names. More specifically, I wanted to account for the case where the column name is "Something.logFC" instead of just "logFC". So I tried modifying the column names by doing the following:

d3.tsv(file, function(error, data) {
    data.forEach(function(d) {
        for (var i=0; i<d3.keys(d).length; i++){
            if(d3.keys(d)[i].indexOf('.') > -1){
                d3.keys(d)[i] = d3.keys(d)[i].split(".")[1];
            }
        };
        d.NAME = d.NAME;
        d.logFC = d.logFC;
        d.logCPM = d.logCPM;
        d.FDR = d.FDR;
        d.PValue = d.PValue
    });

However, now for each data object, new column names are added with values undefined, while the original column names and values are kept the same.

Upvotes: 2

Views: 2424

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

Use this function to locate the dots in the column names and keep only the last part of any name that has a dot:

function removeDot(d){
    Object.keys(d).forEach(function(origProp) {
        var noDot = origProp.split(".")[1];
        if (noDot != undefined) {
          d[noDot] = d[origProp];
          delete d[origProp];
        }
     });
     return d;
};

To use this function, define an accessor like this:

d3.tsv(file, removeDot, function(error, data) {
    //all your code here
});

Note: keep in mind that only d3.csv and d3.tsv accept accessors.

Upvotes: 3

Related Questions