The function pivot_wider()
widens data, converting it from long to wide.
When data is widened:
- The number of rows decreases.
- The number of columns increases.
To widen data two columns are chosen.
- A names column is chosen. These names are used to name the widened columns.
- A values column is chosen. These values populate the widened columns.
Tidyverse reference page
Dataset
For demonstration we’ll load the fisheries_long_tbl
data from the mgrtibbles package (hyperlink includes install instructions).
#Load package
library("mgrtibbles")
#mammal_sleep_tbl tibble for demonstration
mgrtibbles::fisheries_long_tbl
# A tibble: 14,674 × 3
Entity Year Metric_tons
<chr> <dbl> <dbl>
1 Afghanistan 1969 400
2 Afghanistan 1970 400
3 Afghanistan 1971 500
4 Afghanistan 1972 500
5 Afghanistan 1973 500
6 Afghanistan 1974 500
7 Afghanistan 1975 600
8 Afghanistan 1976 600
9 Afghanistan 1977 600
10 Afghanistan 1978 600
# ℹ 14,664 more rows
Long to wide
Pivot the long tibble to a wide tibble.
The two options provided below are:
names_from=
: Column in long data to use as the widened column names.
values_from=
: Column in long data to use as the widened values.
fisheries_long_tbl |> tidyr::pivot_wider(names_from=Year, values_from=Metric_tons) |>
#View first 11 columns with select
dplyr::select(1:11)
# A tibble: 264 × 11
Entity `1969` `1970` `1971` `1972` `1973` `1974` `1975` `1976` `1977` `1978`
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Afgha… 400 4 e2 5 e2 5 e2 5 e2 5 e2 6 e2 6 e2 6 e2 6 e2
2 Afric… 3078461 2.48e6 2.36e6 2.63e6 2.78e6 2.74e6 2.49e6 2.20e6 2.16e6 2.12e6
3 Afric… 850772 9.61e5 1.13e6 1.20e6 1.20e6 1.24e6 1.28e6 1.26e6 1.29e6 1.31e6
4 Alban… 7000 8 e3 8 e3 8 e3 8.00e3 8.45e3 8.41e3 8.38e3 8.34e3 8.81e3
5 Alger… 23150 2.42e4 2.37e4 2.83e4 3.12e4 3.58e4 3.77e4 3.51e4 4.35e4 3.41e4
6 Ameri… 0 0 0 0 1 e2 8.2 e1 1.36e2 1.13e2 2.02e2 1.93e2
7 Andor… NA 0 0 0 0 0 0 0 0 0
8 Angola 425200 3.75e5 3.24e5 6.07e5 4.79e5 4.00e5 1.61e5 8.15e4 1.20e5 1.26e5
9 Antig… 800 9 e2 9 e2 1.2 e3 1.5 e3 1.59e3 1.60e3 1.61e3 1.82e3 1.62e3
10 Arab … 634609 6.88e5 7.05e5 7.53e5 9.21e5 8.99e5 8.64e5 9.34e5 9.05e5 9.10e5
# ℹ 254 more rows