Tidy Data and the Preprocessing Recipe

Hadley Wickham’s tidy-data rules decide what one observation is before any model is fitted. A tidymodels recipe then removes zero- and near-zero-variance predictors, filters correlated ones, imputes, transforms and scales, and is re-estimated inside every resampling fold.
Overview graphic titled 'What Is One Observation?', subtitled 'For Product T, decide what one observation is, build a tidy table, and let every preprocessing step learn only from the training data.' Left, 'The case: Product T': a constructed immediate-release tablet; predict % dissolved at 30 minutes from material and process data. Top row, 'The data: four sources', four panels with photographs: Batch record (granule moisture, lubricant blend time, compression force, tablet press); Certificate of analysis (API particle size D50, API supplier, API lot); In-process test (tablet hardness, sometimes missing); Dissolution (six vessels per batch, % dissolved at 30 min). Bottom row, left to right: '60 batches × 6 vessels per batch = 360 vessel results'; an arrow to 'Group by batch: calculate the mean % dissolved at 30 min across the six vessels for each batch'; an arrow to 'Tidy modeling table: 60 rows (one per batch), one column per variable', with columns Batch, Moisture, Force, Hardness and Mean % dissolved. Right, 'Tidy data rules (Hadley Wickham)': 1, one variable per column; 2, one observation per row; 3, one observational unit per table. Footer: 'The takeaway: the intended prediction defines the observational unit.'
Product T's four data sources, and how 360 vessel results become a 60-row batch table because the prediction is made about batches. Constructed teaching case; photographs are illustrative.

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.

SourceWhat it records
Batch recordGranule moisture, lubricant blend time, compression force, tablet press
Certificate of analysisAPI particle size (D50), API supplier and lot, disintegrant lot
In-process testTablet hardness, sometimes missing
DissolutionSix 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:

  1. Each variable is a column.
  2. Each observation is a row.
  3. 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.

StepThe problem in Product TWhat it does
step_impute_medianHardness missing for 7 batchesFills with the training-set median, which is learned from the data
step_YeoJohnsonAPI D50 is right-skewed; a few coarse lots dominateEstimates a power transformation that makes the distribution more symmetric
step_dummySupplier and press are categoriesConverts each category to 0/1 indicator columns
step_zvA column is constant in this foldRemoves it; many models fail on a zero-variance column
step_nzvPress B made 2 of 60 batchesRemoves predictors dominated by one value
step_corrHardness and compression force correlate at r = 0.94Removes one of each highly correlated pair
step_normalizeForce is in kN, moisture in %Centres each predictor and scales it to unit variance
Graphic titled 'The Preprocessing Recipe', subtitled 'A written, repeatable set of data operations that prepares the training data for modeling and is re-estimated inside every resampling fold.' Left, Product T: predict % dissolved at 30 minutes, 60 batches, 6 vessels per batch, batch-level model, with a tidy data input table of one row per batch (Batch, Moisture, Force, Diss_30). Seven numbered panels: 1, Imputation: a missing hardness value (NA) filled with 48.2, 'e.g., use the training median for hardness'; 2, Transformation: a right-skewed histogram becoming symmetric, 'reduce skewness (e.g., log or Box–Cox)'; 3, Dummy encoding: tablet press A and B converted to 1/0 indicator columns; 4, Zero variance: a flat line, 'remove predictors with no variation'; 5, Near-zero variance: one tall bar and three tiny ones, 'e.g., a press used in only a few batches'; 6, Correlation filtering: a correlation heat map, 'keep one representative (e.g., compression force and press load)'; 7, Normalization: two offset distributions brought onto a common scale. Below, 'The recipe in modeling practice': split data (folds), estimate recipe (on training only), transform training data, fit model, transform held-out data, evaluate predictions. Bottom: 'Pharma perspective: the preprocessing recipe is part of the method, like column, mobile phase and detector settings in an analytical method.' 'Important caveat: statistical filtering cannot replace process knowledge. Removing a variable (e.g., Press B) because it was used in only two batches could eliminate a critical manufacturing signal.' Footer: 'Define the observational unit, then apply a repeatable preprocessing recipe within each fold.'
The seven recipe steps applied to Product T, in the same order as the code above, and where the recipe is estimated in each resampling fold. The figure shows log or Box–Cox as examples of a transformation; the code uses Yeo-Johnson, which also handles zero and negative values.

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

MethodRemovesLearns from other samples?
SNV (standard normal variate)Multiplicative scatter and offset, spectrum by spectrumNo: each spectrum is centred and scaled by its own mean and SD
Savitzky–Golay smoothing and derivativesNoise; baseline offset (1st derivative) and slope (2nd)No: a fixed local polynomial filter
MSC (multiplicative scatter correction)Scatter, relative to a reference spectrumYes: the reference is usually the training-set mean
Mean-centring, autoscaling, PCAOffsets; magnitude differences; collinearityYes

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.

Graphic titled 'Preprocessing Pharmaceutical Spectra', subtitled 'Prepare spectroscopic data so the model sees chemical differences, not artifacts from the instrument or sample.' Left, the case: Product T, NIR spectra of tablets, predict % dissolved at 30 minutes. Five panels, each with a before-and-after sketch: SNV (standard normal variate), three offset spectra collapsing onto one, 'corrects for scatter and pathlength differences within each spectrum (center and scale each spectrum individually)'; Savitzky–Golay (smoothing / derivative), a noisy trace becoming smooth, 'reduces high-frequency noise and can calculate derivatives to better resolve overlapping features'; MSC (multiplicative scatter correction), offset spectra collapsing onto one, 'corrects additive and multiplicative scatter using a reference spectrum from the training data'; Autoscaling (center and scale), two distributions centred on a common scale, 'centers each variable (mean = 0) and scales to unit variance (SD = 1) so all wavelengths contribute on a comparable scale'; PCA, stacked spectra becoming a score plot with three clusters, 'reduces many correlated wavelengths to a few latent variables.' A workflow strip, 'a preprocessing workflow for spectra (training data only)': raw spectra, SNV / MSC, smoothing (Savitzky–Golay), autoscale, PCA (latent variables), model (e.g., dissolution). A table, 'What each step addresses', with a column 'Learns across samples?': SNV, scatter and pathlength differences, no; Savitzky–Golay, noise reduction and derivatives, no (with fixed settings); MSC, additive and multiplicative scatter, yes; autoscaling, different variable scales, yes; PCA, reduce redundancy and extract signal, yes. Key takeaways: use physics-informed steps that reflect the source of variation; estimate any data-driven step (MSC reference, scaling, PCA) using only the training data; apply the same steps to new data. Pharma context: treat preprocessing as part of the analytical method (e.g., per ICH Q14); lock the recipe and document the settings and rationale. Footer: 'Use a consistent, justified preprocessing recipe to turn raw spectra into reliable inputs for modeling.'
The common spectral preprocessing steps, and which of them learn from other samples and must therefore be estimated inside each fold.

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:

    xSNV=x−xˉsx x_{\text{SNV}} = \frac{x - \bar{x}}{s_x}

    Nothing from any other sample is used7.

  • MSC corrects a spectrum using information from a reference spectrum. Each spectrum is regressed against a reference xrefx_{\text{ref}} , usually the mean spectrum of the training set, as x≈a+b xrefx \approx a + b\,x_{\text{ref}} . The fitted offset a and slope b are then removed:

    xMSC=x−ab x_{\text{MSC}} = \frac{x - a}{b}

    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.

Graphic titled 'SNV vs. MSC: What's the Difference?', subtitled 'Both correct scatter effects, but they do it differently and with different assumptions.' Left, 'The problem: scatter': physical differences such as particle size, packing and surface roughness change the offset and slope of NIR spectra without changing chemistry, shown as three parallel offset spectra labelled 'same chemistry, different scatter', above a photograph of tablets and powder. Centre, SNV, standard normal variate: a per-spectrum correction that centres and scales each spectrum by its own mean and standard deviation, removing additive and multiplicative effects for each sample individually, with the formula x prime equals x minus mean of x, divided by sd of x, and a before-and-after sketch of three offset spectra becoming aligned. Right, MSC, multiplicative scatter correction: a reference-based correction across samples that fits each spectrum to a reference, often the mean spectrum, with a linear model and corrects the offset and slope, preserving the reference's shape, with the formula x prime equals x minus a, divided by b, where a is the offset (intercept) and b the slope (scale), and a before-and-after sketch of spectra fitted to the reference. A comparison table: how it works, SNV per spectrum (centre and scale), MSC reference-based (linear fit: offset and slope); learns across samples, SNV no, MSC yes (uses a reference); assumption, SNV each spectrum has its own scatter effects, MSC differences are mainly additive and multiplicative; common use, SNV classification and robust exploratory modeling, MSC quantitative models such as assay or dissolution. 'When to use which?': use SNV for a simple, robust correction when scatter varies from sample to sample; use MSC when you want spectra to match a reference shape, especially for quantitative work; evaluate both during model development and choose based on performance and scientific rationale. Footer: 'Both reduce scatter; SNV standardizes each spectrum, while MSC aligns spectra to a reference.'
SNV standardizes each spectrum against itself; MSC fits each spectrum to a reference spectrum and removes the fitted offset and slope. The 'common use' row is a tendency, not a rule: both are used for quantitative and qualitative models.

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.

Graphic titled 'Data Leakage: When the Model Cheats', subtitled 'Results look better than they really are when information from the test set leaks into model training.' Left, the Product T case: predict % dissolved at 30 minutes, 60 batches, 6 vessels per batch (360 results). Centre, a table, 'Three validation setups — what is being tested?': random vessel split, individual vessel results split at random, tests another measurement from a potentially familiar batch, typical outcome too optimistic (e.g., RMSE 0.9%); grouped batch split, all six vessels for a batch stay together, tests a previously unseen manufacturing batch, more realistic (e.g., RMSE 2.1%); grouped API lot split, all batches from an API lot stay together, tests batches from a previously unseen API lot (new supply), intended use (e.g., RMSE 2.4%). Right, 'The key idea: keep related data together when you split': define the observational unit (e.g., batch or API lot); split by that unit; estimate preprocessing and the model using only the training data. Bottom left, 'How leakage happens': a leaky random split sends vessel V1 of batch B017 to training and vessel V2 to testing, so the model sees batch B017 in both; a correct grouped split keeps all vessels of B017 together in training. Bottom right, 'The correct workflow within each fold': split data (fold), estimate preprocessing (on training only), transform training data, fit model, transform held-out data (same steps), evaluate predictions, with the note 'Preprocessing must be re-estimated inside every resampling fold. Imputation values, scaling parameters, PCA loadings and other data-driven steps are learned from the training data only, then applied to the held-out data.' Footer: 'Avoid leakage, test the right question, and get a performance estimate you can trust.'
Three ways to split Product T, and the question each one actually tests. The stricter the grouping, the higher and more honest the error. RMSE values are illustrative, echoing the NIR example above.

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

Five-panel summary figure. Panel 1, 'What is tidy data?': Hadley Wickham's three rules: each variable is a column; each observation is a row; each type of observational unit is its own table. Panel 2, 'The observational units (Product T)': a dissolution vessel (1 result, % dissolved at 30 min) with an arrow to a tablet representing a batch (1 set of conditions: material, process, release decision); 'Two units, two tables: vessel results (360 rows) and batch data (60 rows), joined by batch_id.' Panel 3, 'Why the unit matters for validation': random cross-validation by vessel, marked with a red cross, splits the vessels of batches 17 and 42 between training (filled circles) and test (open circles) and 'leaks information (the model sees part of a batch in training and the rest in testing)'; grouped cross-validation by batch, marked with a green tick, puts all of batch 17 in training and all of batch 42 in test, which 'keeps whole batches together for a fair test of new batches.' Panel 4, 'The preprocessing recipe (tidymodels)': a recipe document, 'a written plan', leading to five steps (remove zero- and near-zero-variance predictors; filter correlated predictors; impute missing values; transform, e.g. log or Box–Cox; scale, centre and standardize), bracketed as 'estimated inside every resampling fold (training data only)'. Panel 5, 'End-to-end for Product T': tidy tables (vessel, batch), then recipe (preprocessing), then resampling (grouped by batch), then model (e.g. predict % dissolved at 30 min). Footer: 'The one idea: decide what one observation is, then let every preprocessing step that learns from the data learn only from the training data.'
The reading in one figure: tidy-data rules, Product T's two observational units, why random cross-validation by vessel leaks, the recipe estimated inside each fold, and the end-to-end workflow. The figure groups folds by batch; the code above groups by API lot, a stricter version of the same idea.

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

  1. Product T’s vessel table has 360 rows. Give one modeling question for which the vessel is the right observational unit.
  2. step_nzv removes Press B. What evidence would make you put it back?
  3. Why can SNV be applied before splitting, but MSC cannot?
  4. 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.


  1. H. Wickham, “Tidy Data,” Journal of Statistical Software 59(10) (2014). DOI. ↩︎

  2. H. Wickham, M. Çetinkaya-Rundel and G. Grolemund, R for Data Science, 2nd ed. (O’Reilly, 2023). Free online at r4ds.hadley.nz. ↩︎

  3. M. Kuhn and J. Silge, Tidy Modeling with R (O’Reilly, 2022). Chapter 8 on recipes. Free online at tmwr.org. ↩︎

  4. M. Kuhn and K. Johnson, Applied Predictive Modeling (Springer, 2013). Chapter 3, data pre-processing, including the near-zero-variance criteria. DOI. ↩︎ ↩︎

  5. M. Kuhn and K. Johnson, Feature Engineering and Selection (CRC Press, 2019). Free online at feat.engineering. ↩︎

  6. A. Stevens and L. Ramirez-Lopez, prospectr: Miscellaneous functions for processing and sample selection of spectroscopic data, R package. CRAN. ↩︎

  7. 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. ↩︎

  8. 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. ↩︎

  9. 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. ↩︎