Tidy Data and the Preprocessing Recipe
Guidelines:
Modalities:

The one idea
Decide what one observation is, then let every preprocessing step that learns from the data learn only from the training data.
Most modeling failures in regulated work start before the model is chosen. The table had the wrong rows, or a preprocessing step quietly looked at the test set. This reading treats both as part of the method. It also teaches you to read R, the language this week’s code is written in.
The case: Product T
Product T is a constructed immediate-release tablet. Development wants to predict % dissolved at 30 minutes from material and process data so that a slow batch can be anticipated before the dissolution test is run. The same dataset runs through the next two readings.
| Source | What it records |
|---|---|
| Batch record | Granule moisture, lubricant blend time, compression force, tablet press |
| Certificate of analysis | API particle size (D50), API supplier and lot, disintegrant lot |
| In-process test | Tablet hardness, sometimes missing |
| Dissolution | Six vessels per batch, % dissolved at 30 min |
Sixty batches; 360 vessel results.
Hadley Wickham and tidy data
Hadley Wickham, a New Zealand statistician who is now chief scientist at Posit (formerly RStudio), wrote the paper that gives this reading its name. Tidy Data (2014) set out three rules1:
- Each variable is a column.
- Each observation is a row.
- Each type of observational unit is its own table.
The rules sound clerical. They are not. Rule 3 forces the question that decides whether a model can be trusted: what is the unit you are making a prediction about?
Product T has two observational units. A vessel is one dissolution result. A batch is one set of process conditions and one release decision. Putting 360 vessel rows into a model with the batch’s process settings copied onto each row creates six near-identical rows per batch. Random cross-validation will then put vessel 1 of batch 17 in training and vessel 2 in testing, and the model will appear to predict batch 17 when it has, in effect, already seen it.
The classic version of this failure is spectroscopic. An NIR tablet-assay model with three spectra per tablet reported RMSECV 0.9% when random spectra were left out, and 2.1% when whole batches were. The spectrum was not the observational unit; the tablet, and above it the batch, was. Week 11, reading 2 made the same point with whole-batch cross-validation on granule moisture.
Wickham also built much of the toolkit for this: ggplot2 for graphics and dplyr for data manipulation, gathered with other packages as the tidyverse. Max Kuhn’s tidymodels packages, used below, follow the same conventions2,3.
Reading R in five minutes
The code on this site reads top to bottom as a sequence of verbs:
library(tidyverse)
batches <- vessels |> # start with the vessel table
group_by(batch_id) |> # one group per batch
summarise(diss_30 = mean(pct_30min)) |> # batch mean of six vessels
left_join(batch_record, by = "batch_id") # add the process settings
<-assigns a result to a name.|>is the pipe: “take what’s on the left and pass it to the next function”. Read it aloud as then.group_by(),summarise(),left_join()are verbs; each does one thing to a table and returns a table.#starts a comment.
That is enough to follow every snippet this week. The output is a tidy batch table: 60 rows, one per batch, one column per variable.
A recipe is a written preprocessing plan
Kuhn and Johnson’s central argument is that preprocessing is part of the model, not housekeeping done beforehand4,5. tidymodels makes this concrete. A recipe lists the steps; it does not run them until it is estimated on a particular set of data:
library(tidymodels)
rec <- recipe(diss_30 ~ ., data = batches) |>
update_role(batch_id, api_lot, new_role = "id") |> # keep, but don't model
step_impute_median(hardness) |> # fill missing hardness
step_YeoJohnson(api_d50) |> # tame a skewed predictor
step_dummy(all_nominal_predictors()) |> # supplier, press -> 0/1
step_zv(all_predictors()) |> # drop constant columns
step_nzv(all_predictors()) |> # drop near-constant ones
step_corr(all_numeric_predictors(), threshold = 0.9) |>
step_normalize(all_numeric_predictors()) # centre and scale
Each step answers a question the data raise.
| Step | The problem in Product T | What it does |
|---|---|---|
step_impute_median | Hardness missing for 7 batches | Fills with the training-set median, which is learned from the data |
step_YeoJohnson | API D50 is right-skewed; a few coarse lots dominate | Estimates a power transformation that makes the distribution more symmetric |
step_dummy | Supplier and press are categories | Converts each category to 0/1 indicator columns |
step_zv | A column is constant in this fold | Removes it; many models fail on a zero-variance column |
step_nzv | Press B made 2 of 60 batches | Removes predictors dominated by one value |
step_corr | Hardness and compression force correlate at r = 0.94 | Removes one of each highly correlated pair |
step_normalize | Force is in kN, moisture in % | Centres each predictor and scales it to unit variance |

Near-zero variance, specifically
Kuhn’s rule flags a predictor when both are true: the most common value is far more frequent than the second most common (by default a ratio above 95/5), and few values are unique (by default under 10% of rows)4. “Press B” fails both: 58 zeros, 2 ones. It carries almost no information, and in a five-fold split there is a good chance a fold contains no Press B batches at all. At that point it is a zero-variance column inside the fold, which breaks some models and destabilises others.
Removing it is a modeling decision, not a scientific one. If the two Press B batches are the slow ones, you have lost a signal. Check what step_nzv removed, then decide with process knowledge.
Correlation filters and spectra
step_corr suits a table of process variables, where two columns measuring nearly the same thing make coefficients unstable. It is the wrong tool for a spectrum. Neighbouring NIR wavelengths correlate above 0.99, so a correlation filter would discard most of the spectrum. For spectra, the answer to collinearity is to model it with latent variables (step_pca, or a PLS model), as Week 11 reading 3 showed.
Spectral preprocessing: what learns, and what doesn’t
| Method | Removes | Learns from other samples? |
|---|---|---|
| SNV (standard normal variate) | Multiplicative scatter and offset, spectrum by spectrum | No: each spectrum is centred and scaled by its own mean and SD |
| Savitzky–Golay smoothing and derivatives | Noise; baseline offset (1st derivative) and slope (2nd) | No: a fixed local polynomial filter |
| MSC (multiplicative scatter correction) | Scatter, relative to a reference spectrum | Yes: the reference is usually the training-set mean |
| Mean-centring, autoscaling, PCA | Offsets; magnitude differences; collinearity | Yes |
That last column is the one that matters for honest validation. SNV and Savitzky–Golay can be applied once, before splitting, because they never look at another sample. Anything that learns a mean, a median, a reference spectrum, a set of removed columns or a set of components has to be learned inside each fold, from that fold’s training data only. The R package prospectr provides SNV and Savitzky–Golay6; derivatives amplify noise, so the window width is itself a tuning choice.

SNV and MSC: the same problem, two different references
SNV and MSC are easy to confuse, because they fix the same physical problem. In diffuse-reflectance NIR, particle size, tablet surface roughness, packing density and the effective optical path length all change how light scatters. Scatter shifts a spectrum up or down (an additive effect) and stretches or shrinks it (a multiplicative effect) without any change in chemistry. Both methods try to remove that physical variation and leave the chemical variation behind.
The difference is where each method gets its correction:
SNV corrects a spectrum using information from itself. Each spectrum x is centred on its own mean and divided by its own standard deviation:
Nothing from any other sample is used7.
MSC corrects a spectrum using information from a reference spectrum. Each spectrum is regressed against a reference , usually the mean spectrum of the training set, as . The fitted offset a and slope b are then removed:
Every corrected spectrum is pulled toward the shape of the reference8.
In practice the two usually give very similar results; Dhanoa and colleagues showed that they are closely related, linear transformations of each other9. The choice matters more for validation than for chemistry. Because the MSC reference is calculated from the training data, it must be recalculated inside each fold and then frozen with the model, and a new sample is corrected against that frozen reference. SNV needs no stored reference at all. Try both during development and choose on cross-validated performance and on the physics of the samples.

Estimate inside the fold, every time
A recipe is estimated with prep() and applied with bake(). You will rarely call either directly. When the recipe is combined with a model and resampled, tidymodels re-estimates it on each fold’s analysis set:
folds <- group_vfold_cv(batches, group = api_lot, v = 5)
group_vfold_cv keeps every batch from one API lot in the same fold. Product T’s realistic future is a new API lot, so that is what the held-out fold should look like. The choice of grouping is a statement about how the model will be used.

To see what a fitted recipe actually did, ask it:
prepped <- prep(rec, training = batches)
tidy(prepped, number = 5) # which columns did step_nzv remove?
The reading on one page

Where the analyst sits
The analyst decides what one observation is, which grouping makes cross-validation resemble real use, and whether a column removed by an automatic filter carried a process signal. Under ICH Q14, the preprocessing sequence is part of the procedure. It is locked with the model, documented and revalidated if changed, just as a column and mobile phase are in an HPLC method.
For discussion
- Product T’s vessel table has 360 rows. Give one modeling question for which the vessel is the right observational unit.
step_nzvremoves Press B. What evidence would make you put it back?- Why can SNV be applied before splitting, but MSC cannot?
- Grouping folds by API lot gives a worse cross-validated error than random folds. Which number do you report, and why?
Bridge back to the week
Next: Many Models, One Question, which puts this recipe in front of eight models built on different mathematics. Return to Week 12.
Sources
Product T and its numbers are constructed for teaching. The NIR leakage example is a composite of commonly reported failures.
H. Wickham, “Tidy Data,” Journal of Statistical Software 59(10) (2014). DOI. ↩︎
H. Wickham, M. Çetinkaya-Rundel and G. Grolemund, R for Data Science, 2nd ed. (O’Reilly, 2023). Free online at r4ds.hadley.nz. ↩︎
M. Kuhn and J. Silge, Tidy Modeling with R (O’Reilly, 2022). Chapter 8 on recipes. Free online at tmwr.org. ↩︎
M. Kuhn and K. Johnson, Applied Predictive Modeling (Springer, 2013). Chapter 3, data pre-processing, including the near-zero-variance criteria. DOI. ↩︎ ↩︎
M. Kuhn and K. Johnson, Feature Engineering and Selection (CRC Press, 2019). Free online at feat.engineering. ↩︎
A. Stevens and L. Ramirez-Lopez, prospectr: Miscellaneous functions for processing and sample selection of spectroscopic data, R package. CRAN. ↩︎
R. J. Barnes, M. S. Dhanoa and S. J. Lister, “Standard Normal Variate Transformation and De-trending of Near-Infrared Diffuse Reflectance Spectra,” Applied Spectroscopy 43(5) (1989) 772–777. DOI. ↩︎
P. Geladi, D. MacDougall and H. Martens, “Linearization and Scatter-Correction for Near-Infrared Reflectance Spectra of Meat,” Applied Spectroscopy 39(3) (1985) 491–500. DOI. ↩︎
M. S. Dhanoa, S. J. Lister, R. Sanderson and R. J. Barnes, “The Link between Multiplicative Scatter Correction (MSC) and Standard Normal Variate (SNV) Transformations of NIR Spectra,” Journal of Near Infrared Spectroscopy 2(1) (1994) 43–47. DOI. ↩︎