Published
Edited
Oct 1, 2019
Insert cell
md`# Grouping data exercise (Oct. 1 2019)`
Insert cell
d3 = require("d3@5") // require the d3 data library
Insert cell
// load in the list of players in the csv
players = d3.tsv("https://gist.githubusercontent.com/lathropd/0d63302f6c3c1014f2cd3846a23967a8/raw/9e7f666b7a2a83fb6d8e444215d7c46a0d60a62b/baseball.tsv")
Insert cell
d3.nest()
.key(d => d.POS) // nest by player position
.entries(players)
Insert cell
positions = d3.nest()
.key(d => d.POS)
.rollup( summarize )
.entries(players)
.map(renameColumnHeadings)
Insert cell
function renameColumnHeadings(d) {
let position = d.key
let count = d.value.count
let average = d.value.meanPay
return {position, count, average}
}
Insert cell
function summarize(players) {
let pay = players.map(d => +d["Average Pay"])
let meanPay = d3.format("$,.2~s")(d3.mean(pay))
let medianPay = d3.median(pay)
let maximumPay = d3.max(pay)
let minimumPay = d3.min(pay)
let totalForPosition = d3.sum(pay)
let count = players.length
return { pay, meanPay, medianPay, maximumPay, minimumPay, totalForPosition, count }
}
Insert cell
import {table} from "@tmcw/tables"
Insert cell
table(positions)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more