Introduction

This vignette describes the use of the new pivot_longer() and pivot_wider() functions. Their goal is to improve the usability of gather() and spread(), and incorporate state-of-the-art features found in other packages.

For some time, it’s been obvious that there is something fundamentally wrong with the design of spread() and gather(). Many people don’t find the names intuitive and find it hard to remember which direction corresponds to spreading and which to gathering. It also seems surprisingly hard to remember the arguments to these functions, meaning that many people (including me!) have to consult the documentation every time.

There are two important new features inspired by other R packages that have been advancing reshaping in R:

  • pivot_longer() can work with multiple value variables that may have different types, inspired by the enhanced melt() and dcast() functions provided by the data.table package by Matt Dowle and Arun Srinivasan.

  • pivot_longer() and pivot_wider() can take a data frame that specifies precisely how metadata stored in column names becomes data variables (and vice versa), inspired by the cdata package by John Mount and Nina Zumel.

In this vignette, you’ll learn the key ideas behind pivot_longer() and pivot_wider() as you see them used to solve a variety of data reshaping challenges ranging from simple to complex.

To begin we’ll load some needed packages. In real analysis code, I’d imagine you’d do with the library(tidyverse), but I can’t do that here since this vignette is embedded in a package.

library(tidyr)
library(dplyr)
library(readr)

Longer

pivot_longer() makes datasets longer by increasing the number of rows and decreasing the number of columns. I don’t believe it makes sense to describe a dataset as being in “long form”. Length is a relative term, and you can only say (e.g.) that dataset A is longer than dataset B.

pivot_longer() is commonly needed to tidy wild-caught datasets as they often optimise for ease of data entry or ease of comparison rather than ease of analysis. The following sections show how to use pivot_longer() for a wide range of realistic datasets.

String data in column names

The relig_income dataset stores counts based on a survey which (among other things) asked people about their religion and annual income:

This dataset contains three variables:

  • religion, stored in the rows,
  • income spread across the column names, and
  • count stored in the cell values.

To tidy it we use pivot_longer():

  • The first argument is the dataset to reshape, relig_income.

  • The second argument describes which columns need to be reshaped. In this case, it’s every column apart from religion.

  • The names_to gives the name of the variable that will be created from the data stored in the column names, i.e. income.

  • The values_to gives the name of the variable that will be created from the data stored in the cell value, i.e. count.

Neither the names_to nor the values_to column exists in relig_income, so we provide them as character strings surrounded in quotes.

Numeric data in column names

The billboard dataset records the billboard rank of songs in the year 2000. It has a form similar to the relig_income data, but the data encoded in the column names is really a number, not a string.

billboard
#> # A tibble: 317 x 79
#>    artist track date.entered   wk1   wk2   wk3   wk4   wk5   wk6   wk7   wk8
#>    <chr>  <chr> <date>       <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1 2 Pac  Baby… 2000-02-26      87    82    72    77    87    94    99    NA
#>  2 2Ge+h… The … 2000-09-02      91    87    92    NA    NA    NA    NA    NA
#>  3 3 Doo… Kryp… 2000-04-08      81    70    68    67    66    57    54    53
#>  4 3 Doo… Loser 2000-10-21      76    76    72    69    67    65    55    59
#>  5 504 B… Wobb… 2000-04-15      57    34    25    17    17    31    36    49
#>  6 98^0   Give… 2000-08-19      51    39    34    26    26    19     2     2
#>  7 A*Tee… Danc… 2000-07-08      97    97    96    95   100    NA    NA    NA
#>  8 Aaliy… I Do… 2000-01-29      84    62    51    41    38    35    35    38
#>  9 Aaliy… Try … 2000-03-18      59    53    38    28    21    18    16    14
#> 10 Adams… Open… 2000-08-26      76    76    74    69    68    67    61    58
#> # … with 307 more rows, and 68 more variables: wk9 <dbl>, wk10 <dbl>,
#> #   wk11 <dbl>, wk12 <dbl>, wk13 <dbl>, wk14 <dbl>, wk15 <dbl>, wk16 <dbl>,
#> #   wk17 <dbl>, wk18 <dbl>, wk19 <dbl>, wk20 <dbl>, wk21 <dbl>, wk22 <dbl>,
#> #   wk23 <dbl>, wk24 <dbl>, wk25 <dbl>, wk26 <dbl>, wk27 <dbl>, wk28 <dbl>,
#> #   wk29 <dbl>, wk30 <dbl>, wk31 <dbl>, wk32 <dbl>, wk33 <dbl>, wk34 <dbl>,
#> #   wk35 <dbl>, wk36 <dbl>, wk37 <dbl>, wk38 <dbl>, wk39 <dbl>, wk40 <dbl>,
#> #   wk41 <dbl>, wk42 <dbl>, wk43 <dbl>, wk44 <dbl>, wk45 <dbl>, wk46 <dbl>,
#> #   wk47 <dbl>, wk48 <dbl>, wk49 <dbl>, wk50 <dbl>, wk51 <dbl>, wk52 <dbl>,
#> #   wk53 <dbl>, wk54 <dbl>, wk55 <dbl>, wk56 <dbl>, wk57 <dbl>, wk58 <dbl>,
#> #   wk59 <dbl>, wk60 <dbl>, wk61 <dbl>, wk62 <dbl>, wk63 <dbl>, wk64 <dbl>,
#> #   wk65 <dbl>, wk66 <lgl>, wk67 <lgl>, wk68 <lgl>, wk69 <lgl>, wk70 <lgl>,
#> #   wk71 <lgl>, wk72 <lgl>, wk73 <lgl>, wk74 <lgl>, wk75 <lgl>, wk76 <lgl>

We can start with the same basic specification as for the relig_income dataset. Here we want the names to become a variable called week, and the values to become a variable called rank. I also use values_drop_na to drop rows that correspond to missing values. Not every song stays in the charts for all 76 weeks, so the structure of the input data force the creation of unnessary explicit NAs.

It would be nice to easily determine how long each song stayed in the charts, but to do that, we’ll need to convert the week variable to an integer. We can do that by using two additional arguments: names_prefix strips off the wk prefix, and names_ptypes specifies that week should be an integer:

Many variables in column names

A more challenging situation occurs when you have multiple variables crammed into the column names. For example, take the who dataset:

who
#> # A tibble: 7,240 x 60
#>    country iso2  iso3   year new_sp_m014 new_sp_m1524 new_sp_m2534 new_sp_m3544
#>    <chr>   <chr> <chr> <int>       <int>        <int>        <int>        <int>
#>  1 Afghan… AF    AFG    1980          NA           NA           NA           NA
#>  2 Afghan… AF    AFG    1981          NA           NA           NA           NA
#>  3 Afghan… AF    AFG    1982          NA           NA           NA           NA
#>  4 Afghan… AF    AFG    1983          NA           NA           NA           NA
#>  5 Afghan… AF    AFG    1984          NA           NA           NA           NA
#>  6 Afghan… AF    AFG    1985          NA           NA           NA           NA
#>  7 Afghan… AF    AFG    1986          NA           NA           NA           NA
#>  8 Afghan… AF    AFG    1987          NA           NA           NA           NA
#>  9 Afghan… AF    AFG    1988          NA           NA           NA           NA
#> 10 Afghan… AF    AFG    1989          NA           NA           NA           NA
#> # … with 7,230 more rows, and 52 more variables: new_sp_m4554 <int>,
#> #   new_sp_m5564 <int>, new_sp_m65 <int>, new_sp_f014 <int>,
#> #   new_sp_f1524 <int>, new_sp_f2534 <int>, new_sp_f3544 <int>,
#> #   new_sp_f4554 <int>, new_sp_f5564 <int>, new_sp_f65 <int>,
#> #   new_sn_m014 <int>, new_sn_m1524 <int>, new_sn_m2534 <int>,
#> #   new_sn_m3544 <int>, new_sn_m4554 <int>, new_sn_m5564 <int>,
#> #   new_sn_m65 <int>, new_sn_f014 <int>, new_sn_f1524 <int>,
#> #   new_sn_f2534 <int>, new_sn_f3544 <int>, new_sn_f4554 <int>,
#> #   new_sn_f5564 <int>, new_sn_f65 <int>, new_ep_m014 <int>,
#> #   new_ep_m1524 <int>, new_ep_m2534 <int>, new_ep_m3544 <int>,
#> #   new_ep_m4554 <int>, new_ep_m5564 <int>, new_ep_m65 <int>,
#> #   new_ep_f014 <int>, new_ep_f1524 <int>, new_ep_f2534 <int>,
#> #   new_ep_f3544 <int>, new_ep_f4554 <int>, new_ep_f5564 <int>,
#> #   new_ep_f65 <int>, newrel_m014 <int>, newrel_m1524 <int>,
#> #   newrel_m2534 <int>, newrel_m3544 <int>, newrel_m4554 <int>,
#> #   newrel_m5564 <int>, newrel_m65 <int>, newrel_f014 <int>,
#> #   newrel_f1524 <int>, newrel_f2534 <int>, newrel_f3544 <int>,
#> #   newrel_f4554 <int>, newrel_f5564 <int>, newrel_f65 <int>

country, iso2, iso3, and year are already variables, so they can be left as is. But the columns from new_sp_m014 to newrel_f65 encode four variables in their names:

  • The new_/new prefix indicates these are counts of new cases. This dataset only contains new cases, so we’ll ignore it here because it’s constant.

  • sp/rel/sp/ep describe how the case was diagnosed.

  • m/f gives the gender.

  • 014/1524/2535/3544/4554/65 supplies the age range.

We can break these variables up by specifying multiple column names in names_to, and then either providing names_sep or names_pattern. Here names_pattern is the most natural fit. It has a similar interface to extract: you give it a regular expression containing groups (defined by ()) and it puts each group in a column.

We could go one step further and specify the types of the gender and age columns. I think this is good practice when you have categorical variables with a known set of values.

Multiple observations per row

So far, we have been working with data frames that have one observation per row, but many important pivotting problems involve multiple observations per row. You can usually recognise this case because name of the column that you want to appear in the output is part of the column name in the input. In this section, you’ll learn how to pivot this sort of data.

The following example is adapted from the data.table vignette, as inspiration for tidyr’s solution to this problem.

Note that we have two pieces of information (or values) for each child: their gender and their dob (date of birth). These need to go into separate columns in the result. Again we supply multiple variables to names_to, using names_sep to split up each variable name. Note the special name .value: this tells pivot_longer() that that part of the column name specifies the “value” being measured (which will become a variable in the output).

Note the use of values_drop_na = TRUE: the input shape forces the creation of explicit missing variables for observations that don’t exist.

This problem also exists in the anscombe dataset built in to base R:

This dataset contains four pairs of variables (x1 and y1, x2 and y2, etc) that underlie Anscombe’s quartet, a collection of four datasets that have the same summary statistics (mean, sd, correlation etc), but have quite different data. We want to produce a dataset with columns set, x and y.

A similar situation can arise with panel data. For example, take this example dataset provided by Thomas Leeper. We can tidy it using the same approach as for anscombe:

Duplicated column names

Occassionally you will come across datasets that have duplicated column names. Generally, such datasets are hard to work with in R, because when you refer to a column by name it only finds the first match. To create a tibble with duplicated names, you have to explicitly opt out of the name repair that usually prevents you from creating such a dataset:

When pivot_longer() encounters such data, it automatically adds another column to the output:

Wider

pivot_wider() is the opposite of pivot_longer(): it makes a dataset wider by increasing the number of columns and decreasing the number of rows. It’s relatively rare to need pivot_wider() to make tidy data, but it’s often useful for creating summary tables for presentation, or data in a format needed by other tools.

Capture-recapture data

The fish_encounters dataset, contributed by Myfanwy Johnston, describes when fish swimming down a river are detected by automatic monitoring stations:

Many tools used to analyse this data need it in a form where each station is a column:

This dataset only records when a fish was detected by the station - it doesn’t record when it wasn’t detected (this is common with this type of data). That means the output data is filled with NAs. However, in this case we know that the absence of a record means that the fish was not seen, so we can ask pivot_wider() to fill these missing values in with zeros:

Aggregation

You can also use pivot_wider() to perform simple aggregation. For example, take the warpbreaks dataset built in to base R (converted to a tibble for the better print method):

This is a designed experiment with nine replicates for every combination of wool (A and B) and tension (L, M, H):

What happens if we attempt to pivot the levels of wool into the columns?

We get a warning that each cell in the output corresponds to multiple cells in the input. The default behaviour produces list-columns, which contain all the individual values. A more useful output would be summary statistics, e.g. mean breaks for each combination of wool and tension:

For more complex summary operations, I recommend summarising before reshaping, but for simple cases it’s often convenient to summarise within pivot_wider().

Contact list

A final challenge is inspired by Jiena Gu. Imagine you have a contact list that you’ve copied and pasted from a website:

This is challenging because there’s no variable that identifies which observations belong together. We can fix this by noting that every contact starts with a name, so we can create a unique id by counting every time we see “name” as the field:

Now that we have a unique identifier for each person, we can pivot field and value into the columns:

Longer, then wider

Some problems can’t be solved by pivotting in a single direction. The examples in this section show how you might combine pivot_longer() and pivot_wider() to solve more complex problems.

World bank

world_bank_pop contains data from the World Bank about population per country from 2000 to 2018.

My goal is to produce a tidy dataset where each variable is in a column. It’s not obvious exactly what steps are needed yet, but I’ll start with the most obvious problem: year is spread across multiple columns.

Next we need to consider the indicator variable:

Here SP.POP.GROW is population growth, SP.POP.TOTL is total population, and SP.URB.* are the same but only for urban areas. Let’s split this up into two variables: area (total or urban) and the actual variable (population or growth):

Now we can complete the tidying by pivoting variable and value to make TOTL and GROW columns:

Multi-choice

Based on a suggestion by Maxime Wack, https://github.com/tidyverse/tidyr/issues/384), the final example shows how to deal with a common way of recording multiple choice data. Often you will get such data as follows:

But the actual order isn’t important, and you’d prefer to have the individual questions in the columns. You can achieve the desired transformation in two steps. First, you make the data longer, eliminating the explcit NAs, and adding a column to indicate that this choice was chosen:

Then you make the data wider, filling in the missing observations with FALSE:

Manual specs

The arguments to pivot_longer() and pivot_wider() allow you to pivot a wide range of datasets. But the creativity that people apply to their data structures is seemingly endless, so it’s quite possible that you will encounter a dataset that you can’t immediately see how to reshape with pivot_longer() and pivot_wider(). To gain more control over pivotting, you can instead create a “spec” data frame that describes exactly how data stored in the column names becomes variables (and vice versa). This section introduces you to the spec data structure, and show you how to use it when pivot_longer() and pivot_wider() are insufficient.

Longer

To see how this works, lets return to the simplest case of pivotting applied to the relig_income dataset. Now pivotting happens in two steps: we first create a spec object (using build_longer_spec()) then use that to describe the pivotting operation:

(This gives the same result as before, just with more code. There’s no need to use it here, it is presented as a simple example for using spec.)

What does spec look like? It’s a data frame with one row for each column, and two special columns that start with .:

  • .name gives the name of the column.
  • .value gives the name of the column that the values in the cells will go into.

Wider

Below we widen us_rent_income with pivot_wider(). The result is ok, but I think it could be improved:

I think it would be better to have columns income, rent, income_moe, and rent_moe, which we can achieve with a manual spec. The current spec looks like this:

For this case, we mutate spec to carefully construct the column names:

Supplying this spec to pivot_wider() gives us the result we’re looking for:

By hand

Sometimes it’s not possible (or not convenient) to compute the spec, and instead it’s more convenient to construct the spec “by hand”. For example, take this construction data, which is lightly modified from Table 5 “completions” found at https://www.census.gov/construction/nrc/index.html:

This sort of data is not uncommon from government agencies: the column names actually belong to different variables, and here we have summaries for number of units (1, 2-4, 5+) and regions of the country (NE, NW, midwest, S, W). We can most easily describe that with a tibble:

Which yields the following longer form:

Note that there is no overlap between the units and region variables; here the data would really be most naturally described in two independent tables.