Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cross(a, b[, f]) #50

Closed
mbostock opened this issue Feb 7, 2017 · 1 comment
Closed

cross(a, b[, f]) #50

mbostock opened this issue Feb 7, 2017 · 1 comment
Assignees

Comments

@mbostock
Copy link
Member

mbostock commented Feb 7, 2017

Proposed:

function pair(a, b) {
  return [a, b];
}

d3.cross = function(a, b, f) {
  var na = a.length, nb = b.length, c = new Array(na * nb), ia, ib, ic, va;
  if (f == null) f = pair;
  for (ia = ic = 0; ia < na; ++ia) for (va = a[ia], ib = 0; ib < nb; ++ib, ++ic) c[ic] = f(va, b[ib]);
  return c;
};

For example, given the following CSV data:

Year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec,J-D,D-N,DJF,MAM,JJA,SON
1880,-.30,-.21,-.18,-.27,-.14,-.29,-.24,-.08,-.17,-.16,-.19,-.22,-.20,***,***,-.20,-.20,-.17
1881,-.10,-.14,.01,-.03,-.04,-.28,-.07,-.03,-.09,-.20,-.26,-.16,-.12,-.12,-.15,-.02,-.13,-.19
1882,.09,.08,.01,-.20,-.18,-.25,-.11,.03,-.01,-.23,-.21,-.25,-.10,-.09,.00,-.12,-.11,-.15
1883,-.34,-.42,-.18,-.25,-.26,-.13,-.09,-.14,-.19,-.12,-.21,-.19,-.21,-.22,-.34,-.23,-.12,-.18
1884,-.18,-.13,-.36,-.36,-.32,-.38,-.35,-.27,-.24,-.22,-.30,-.30,-.28,-.28,-.17,-.35,-.33,-.25
1885,-.66,-.30,-.24,-.45,-.42,-.50,-.29,-.27,-.19,-.20,-.22,-.07,-.32,-.33,-.42,-.37,-.35,-.20
1886,-.43,-.46,-.41,-.29,-.27,-.39,-.16,-.31,-.19,-.25,-.26,-.25,-.31,-.29,-.32,-.33,-.29,-.23
1887,-.66,-.48,-.32,-.37,-.33,-.21,-.19,-.28,-.19,-.32,-.25,-.38,-.33,-.32,-.46,-.34,-.22,-.26
…

You could say:

d3.csv("temperatures.csv")
  .then(data => d3.cross(data.columns.slice(1, 13), data, (month, d) => ({
    date: d.Year + "-" + month,
    temperature: d[month]
  })))
@curran
Copy link

curran commented Feb 7, 2017

This would be awesome.

The term "melt" is used for a similar operation in the R world. See

Here's a nice article on this topic by @eagereyes - Spreadsheet Thinking vs. Database Thinking.

Also, it would be interesting to consider how this would behave on sparse data. For example, would the operation let us get from this child mortality data from Gapminder to Lines with Missing Data?

@mbostock mbostock self-assigned this Feb 28, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants