tidyr::pivot_wider()
   get_help() docs


Description

The pivot_wider() function is part of the {tidyr} package, which is part of the {tidyverse}.

We use this function to convert a long tibble (data frame) into a wide tibble (data frame).

To use this function, you need to either first load the {tidyr} library, or always use the function with tidyr::pivot_wider() notation.

# Load the library
library(tidyr)
# Or, load the full tidyverse:
library(tidyverse)

# Or, use :: notation
tidyr::pivot_wider()

Conceptual Usage

tibble %>% 
  pivot_wider(names_from = "column whose values will become new column names",
              values_from = "column whose values will be in those new columns")

Examples

This example uses the dataset tb_cases_long, a long tibble which shows how many cases of Tuberculosis were recorded in each country in the given year.

tb_cases_long
## # A tibble: 6 × 3
##   country      year  cases
##   <chr>       <int>  <int>
## 1 Afghanistan  1999    745
## 2 Afghanistan  2000   2666
## 3 Brazil       1999  37737
## 4 Brazil       2000  80488
## 5 China        1999 212258
## 6 China        2000 213766
# Pivot tb_cases wider
tb_cases_long %>% 
  pivot_wider(names_from = "year", # new columns will be created from values in `year`
              values_from = "cases") # those new columns contain values from `cases`
## # A tibble: 3 × 3
##   country     `1999` `2000`
##   <chr>        <int>  <int>
## 1 Afghanistan    745   2666
## 2 Brazil       37737  80488
## 3 China       212258 213766