Introduction
tidyr provides tools for tidying data. pivot_longer() and pivot_wider() transform data between long and wide formats.
Pivot Longer
library(tidyr)
df <- tibble(
id = 1:2,
treatment = c("A", "B"),
result1 = c(10, 20),
result2 = c(15, 25)
)
# Convert to long format
df %>%
pivot_longer(cols = c(result1, result2),
names_to = "measurement",
values_to = "value")
Pivot Wider
df <- tibble(
id = c(1, 1, 2, 2),
type = c("pre", "post", "pre", "post"),
value = c(10, 15, 20, 25)
)
# Convert to wide format
df %>%
pivot_wider(names_from = type,
values_from = value)
Summary
pivot_longer() and pivot_wider() transform data structure. Use the appropriate format for your analysis.