Tidy Data
Tidy Data is a way of laying out a data set so that it can be modelled directly. The term is from Hadley Wickham, and Grolemund and Wickham build their data-wrangling toolkit on it. A data set is tidy when
- each variable is a column,
- each observation is a row, and
- each value is a cell.
A Generalized Linear Model expects its input in exactly this shape. A tidy data set of n observations of p variables is the matrix
\mathbf{X} = \begin{bmatrix} x_{11} & \cdots & x_{1p} \\ \vdots & & \vdots \\ x_{n1} & \cdots & x_{np} \end{bmatrix}
x_{ij}is the value of variablejfor observationi, withi = 1, \dots, nandj = 1, \dots, p.
Python's pandas uses the same idea: a DataFrame with one row per observation. McKinney covers the loading, cleaning and reshaping steps.
The unit of observation
Choosing the unit of observation is the first modelling decision. In a rating model a row is usually one policy, vehicle or policy-term. A frequency model is fit at the policy (or policy-term) level, so claim-level data must be aggregated — claims counted and losses summed by policy — and then joined to the policy data. A left join keeps the policies with no claims.
What tidy table does a frequency and severity model need from these two tables? A policy table has three policies, P1, P2 and P3, each with
1.0car-year. A claim table has four claims:
Policy Claim ($) P1 2,000 P1 500 P3 8,000 P3 1,500 Answer
- Aggregate the claims by policy: P1 has 2 claims and
\$2{,}500, P3 has 2 claims and\$9{,}500.- Left-join the summary onto the policy table, so P2 keeps its row with zero claims:
Policy Exposure Claim count Losses P1 1.0 2 2,500 P2 1.0 0 0 P3 1.0 2 9,500
- Overall frequency is
4/3 = 1.33claims per car-year.- An inner join would have dropped P2, and with it a claim-free car-year, overstating frequency at
4/2 = 2.0.
Common untidy layouts
Three layouts break the rules. A wide table has one column per year, so it is pivoted longer to make year a variable. A column packing two variables into one value ("M-35") is separated. One observation split across several tables is joined on a key.
A territory summary has columns
territory,2022,2023and2024, each holding earned exposure. Is it tidy, and what should it become?
- It is not tidy. Year is a variable, but it is stored in the column headers, and exposure is spread across three columns.
- Pivoting longer gives three columns,
territory,yearandexposure, with one row per territory-year.- A model can now use
yearas a predictor (for trend) andexposureas a weight or offset.
Joining without checking the row count A one-to-many key silently duplicates policies and inflates exposure. After any join, check that the row count is what it should be. This is a data quality check, not a formality.