9  Reshaping Data: Wide vs. Long

NoteWhat you’ll be able to do

By the end of this chapter you will be able to:

  1. Distinguish wide from long format, and identify which shape your analysis needs.
  2. Convert between the two with the tidyr pivot functions.
  3. Reshape several measurements at once.
  4. Diagnose the most common reshape errors before they reach your analysis.

Data can be stored in two fundamentally different shapes, and many mistakes with repeated measures start with the data being in the wrong shape for the analysis you want to do. This chapter explains the difference and shows you how to flip between them.

9.1 Two ways to store the same data

Imagine you measure each participant’s cortisol level at three time points: baseline, 30 minutes after a stressor, and 60 minutes after. (Here t1–t3 just mean “time 1–3.” In the Cambridge data later in this chapter, t stands for testosterone and cortisol is c.)

9.1.1 Wide format

In wide format, each participant gets one row, and each time point gets its own column.

subject win t1 t2 t3
1 yes 12 18 14
2 no 10 11 10
3 yes 14 22 17

This is intuitive for data entry. It is also what t.test(before, after, paired = TRUE) expects.

9.1.2 Long format

In long format, each observation gets its own row. The time point becomes a variable in its own right.

subject win time cortisol
1 yes 1 12
1 yes 2 18
1 yes 3 14
2 no 1 10
2 no 2 11
2 no 3 10
3 yes 1 14
3 yes 2 22
3 yes 3 17

Long format looks less compact, but it is what ggplot2, repeated-measures ANOVA in afex, and linear mixed-effects models all expect.

9.2 When to use which

Format Use it when… Functions that prefer it
Wide One row per subject t.test() paired (with two columns), Excel-style spreadsheets, summary tables
Long One row per observation ggplot2, aov() with within-subject factors, afex::aov_ez(), mixed-effects models, group-by analyses

If you find yourself thinking, “I want to color points by time on a plot,” or “I want to run a repeated-measures ANOVA across t1, t2, t3,” you need long format. If you find yourself thinking, “I want to compare t1 and t3 for each subject as a paired test,” you can stay wide.

9.3 Reshaping in R with tidyr

The tidyr package (loaded as part of library(tidyverse)) provides two functions that do nearly all the reshaping you’ll ever need:

  • pivot_longer() — wide to long
  • pivot_wider() — long to wide

9.3.1 Wide to long: the standard case

Suppose your data look like this:

data
# A tibble: 3 × 5
  subject win      t1    t2    t3
    <int> <chr> <dbl> <dbl> <dbl>
1       1 yes      12    18    14
2       2 no       10    11    10
3       3 yes      14    22    17

To convert the three time-point columns into a single cortisol column with a time indicator:

library(tidyverse)

long_data <- pivot_longer(data,
                          cols = c(t1, t2, t3),
                          names_to = "time",
                          values_to = "cortisol")
subject win time cortisol
1 yes t1 12
1 yes t2 18
1 yes t3 14
2 no t1 10
… … … …

The time column is still character-typed ("t1", "t2", "t3"). To get a numeric time variable:

long_data$time <- as.numeric(gsub("t", "", long_data$time))

gsub("t", "", ...) strips the “t” prefix, leaving the numeric portion as a string; as.numeric() converts.

9.3.2 Long to wide

The reverse direction is pivot_wider():

wide_data <- pivot_wider(long_data,
                        names_from = "time",
                        values_from = "cortisol",
                        names_prefix = "t")

names_from says which column’s values should become new column names; values_from says which column fills the cells. names_prefix = "t" re-creates the t1, t2, t3 style.

9.4 Reshaping multiple measurements at once

Real datasets often have several variables that repeat across time. The Cambridge/Humboldt fellowship study (covered in Chapter 32) is a clear example: testosterone (t1, t2, t3), estradiol (e1, e2, e3), progesterone (p1, p2, p3), and cortisol (c1, c2, c3) all measured at the same three time points.

If you do this naively with pivot_longer(cols = c(t1, t2, ..., c3)), you’ll get a single value column that mixes all four hormones — not what you want. Instead, use the names_pattern argument with a .value placeholder.

data <- read.csv("https://jkoxford-a11y.github.io/awesomesaucestats/data/cambridge_humboldt.csv")

long_df <- pivot_longer(data,
                        cols = t1:c3,
                        names_to = c(".value", "time"),
                        names_pattern = "^([tepc])([1-3])$")

Here’s what’s happening:

  • cols = t1:c3 — pivot only the twelve hormone columns, which sit side by side in the file from t1 to c3. Every other column (age, condition, and so on) is kept and repeated on each of a subject’s rows.
  • names_pattern = "^([tepc])([1-3])$" — a regular expression that captures two groups: the hormone letter and the time digit. The ^ and $ pin the match to the whole column name.
  • names_to = c(".value", "time") — the first captured group (the letter) becomes a new column name; the second captured group (the digit) becomes the value of a new time column.

The result has one row per subject per time point, 990 rows for 330 subjects, with the four hormones in their own columns t, e, p, and c, plus all the non-repeated columns. Then convert time to numeric:

long_df$time <- as.numeric(long_df$time)

This pattern — .value plus a regex with two capture groups — is the trick that makes hormone or repeated-measurement datasets tidy in one step.

WarningPivot only the columns that repeat

Writing cols = -c(subject, win) (everything except the IDs) looks equivalent, but on the Cambridge file it silently wrecks the data. The other 15 columns don’t fit the pattern, so they become 4,950 empty rows, and the unanchored pattern ([a-z])([1-3]) finds t1 inside htt1, so every time point appears twice with the wrong testosterone values. The result has 6,930 rows instead of 990, with no error. Name the repeating columns explicitly, anchor the pattern, and check the row count: subjects × time points.

9.5 A complete worked example

Because pivot_longer() keeps every column you don’t pivot, the whole Cambridge reshape is one call:

library(tidyverse)

data <- read.csv("https://jkoxford-a11y.github.io/awesomesaucestats/data/cambridge_humboldt.csv")

merged_data <- pivot_longer(data,
                            cols = t1:c3,
                            names_to = c(".value", "time"),
                            names_pattern = "^([tepc])([1-3])$")
merged_data$time <- as.numeric(merged_data$time)

nrow(merged_data)   # 990 = 330 subjects × 3 time points

The same result can be built step by step, which makes each move visible: set aside the columns that don’t repeat, pivot the ones that do, and join them back together. This is the original course recipe for the Cambridge study, and it produces an identical dataset:


# Step 1: Set aside the non-repeated columns
df_no_repeats <- data %>%
  select(-c(t1, t2, t3, e1, e2, e3,
            p1, p2, p3, c1, c2, c3))

# Step 2: Take just the repeated-measures columns plus IDs
subset_df <- data %>%
  select(subject, win, t1, t2, t3, e1, e2, e3,
                       p1, p2, p3, c1, c2, c3)

# Step 3: Pivot to long, with .value capturing the hormone letter
long_df <- pivot_longer(subset_df,
                        cols = -c(subject, win),
                        names_to = c(".value", "time"),
                        names_pattern = "^([tepc])([1-3])$")

# Step 4: Convert time to numeric
long_df$time <- as.numeric(long_df$time)

# Step 5: Merge the reshaped data back with the non-repeated columns
merged_data <- left_join(df_no_repeats, long_df,
                        by = c("subject", "win"))

# Step 6: Write to disk if you want a copy
write.csv(merged_data, "merged_dataset.csv", row.names = FALSE)

After this runs, merged_data is the dataset you’d feed to afex::aov_ez() for a repeated-measures ANOVA, or to ggplot() for a time-series plot grouped by win/loss.

9.6 A note on dplyr pipes

You’ll see the %>% operator a lot in tidyverse code. It’s the pipe: x %>% f() is equivalent to f(x), just written left-to-right. You can chain operations:

data %>%
  select(-c(t1, t2, t3)) %>%
  filter(!is.na(subject)) %>%
  pivot_longer(...)

Reads as “take data, drop those columns, drop missing subjects, pivot.” The native R pipe |> (available since R 4.1) does almost the same thing — both work.

9.7 Common reshape errors

Error What it means Fix
Warning after pivot_wider: values “are not uniquely identified; output will contain list-cols” More than one row maps to the same new cell — an ID column is missing, or the data contain true duplicate rows. The result has list-columns that break later steps Make sure every column that identifies a row (e.g., subject) is still in the data; find and remove true duplicates
Wrong number of rows after pivot_longer You included a non-repeated column in cols, excluded a repeated one, or the name pattern matched columns it shouldn’t Name the repeating columns explicitly, anchor the pattern with ^ and $, and check that rows = subjects × time points
time ends up as character Expected: anything pulled out of a column name is text as.numeric() after the pivot, or add names_transform = list(time = as.numeric) to the pivot_longer() call
A column disappeared after pivot_wider You set id_cols to only some columns; anything not in id_cols, names_from, or values_from is dropped. (pivot_longer does not drop columns — anything not in cols is kept and repeated.) List every column you want to keep in id_cols, or leave id_cols out

9.8 When to do this in Excel instead

For very small datasets — say, three subjects and three time points — you can reshape by hand in Excel and re-import. For anything bigger, doing it by hand is slow and error-prone. pivot_longer and pivot_wider are the right tools.

With your data clean and in the right shape, Part III turns to the assumption checks you’ll do before nearly every test: normality, transformations, and the non-parametric fallback when normality fails.


TipChapter Summary

Core idea: The same data can live in wide format (one row per subject) or long format (one row per observation). Most repeated-measures mistakes start with data in the wrong shape for the analysis.

You should understand:

  • Wide format suits paired t-tests and data entry; long format suits repeated-measures ANOVA and ggplot
  • Why pivot_longer() needs to know which columns repeat and which identify the subject
  • What the common reshape errors mean and how to fix them

You should be able to do in R:

  • Wide → long: pivot_longer(cols = ..., names_to = ..., values_to = ...)
  • Long → wide: pivot_wider(names_from = ..., values_from = ...)
  • Check the result: row count and str() after every pivot

Plain-language check: A classmate’s repeated-measures data has columns t1, t2, t3 and they want to run aov_ez(). What has to happen first, and why?

The one mistake to avoid: Pivoting and not checking the result. A reshape that “ran without errors” can still silently drop a column or produce the wrong number of rows — always verify against what you expected.

Practice: Take a wide dataset with three time-point columns and reshape it to long. How many rows should the result have if there are 20 subjects? Verify.

Key terms from this chapter are defined in the Glossary.

NoteReshaping Practice

Practice the skills from this chapter using real data: Reshaping Practice: Cognitive Task Performance.