library(dplyr)
library(tidyr)
bfi_small_wide <- bfi_small_long %>%
pivot_wider(
names_from = item,
values_from = response
)From Long to Wide
Sometimes we need to reverse the transformation. Imagine we start from a long dataset like the one above and want to restore the original columns—this time using pivot_wider():
The resulting dataset has one row per participant (id) and separate columns for A1, A2, and A3 again. pivot_wider() is especially useful when creating summary tables or preparing data for export.
Dealing with Missing Values
Pivoting can introduce missing values when not every subject has measurements in every category. pivot_wider() gives you a simple way to fill missing cells with a chosen value:
bfi_small_long %>%
pivot_wider(
names_from = item,
values_from = response,
values_fill = 0 # or NA, or any other placeholder
)# A tibble: 2,800 × 4
id A1 A2 A3
<int> <int> <int> <int>
1 1 2 4 3
2 2 2 4 5
3 3 5 4 5
4 4 4 4 6
5 5 2 3 3
6 6 6 6 5
7 7 2 5 5
8 8 4 3 1
9 9 4 3 6
10 10 2 5 6
# ℹ 2,790 more rows
This is useful for preparing matrices for models or visualizations that require complete grids.
Transform the this long dataset back to wide format using pivot_wider(), ensuring that missing values are filled with -1.
# A tibble: 6 × 3
id variable value
<dbl> <chr> <dbl>
1 1 X 10
2 1 Y 20
3 2 X 30
4 3 X 40
5 3 Y 50
6 3 Z 60
long_data %>%
pivot_wider(
names_from = variable,
values_from = value,
values_fill = -1
)# A tibble: 3 × 4
id X Y Z
<dbl> <dbl> <dbl> <dbl>
1 1 10 20 -1
2 2 30 -1 -1
3 3 40 50 60