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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more