2021-03-03 23:20:37 +08:00
# Data tidying {#data-tidy}
2016-07-24 22:16:08 +08:00
## Introduction
2022-02-24 07:17:19 +08:00
> "Happy families are all alike; every unhappy family is unhappy in its own way." --- Leo Tolstoy
2016-07-26 00:28:05 +08:00
2022-02-24 07:17:19 +08:00
> "Tidy datasets are all alike, but every messy dataset is messy in its own way." --- Hadley Wickham
2015-07-29 00:16:58 +08:00
2022-02-24 07:17:19 +08:00
In this chapter, you will learn a consistent way to organize your data in R using a system called **tidy data**.
Getting your data into this format requires some work up front, but that work pays off in the long term.
Once you have tidy data and the tidy tools provided by packages in the tidyverse, you will spend much less time munging data from one representation to another, allowing you to spend more time on the data questions you care about.
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
This chapter will give you a practical introduction to tidy data and the accompanying tools in the **tidyr** package.
If you'd like to learn more about the underlying theory, you might enjoy the *Tidy Data* paper published in the Journal of Statistical Software, <http://www.jstatsoft.org/v59/i10/paper>.
2015-07-29 00:16:58 +08:00
2016-07-19 21:01:50 +08:00
### Prerequisites
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
In this chapter we'll focus on tidyr, a package that provides a bunch of tools to help tidy up your messy datasets.
tidyr is a member of the core tidyverse.
2016-07-26 00:28:05 +08:00
2016-07-27 21:23:28 +08:00
```{r setup, message = FALSE}
2016-10-04 01:30:24 +08:00
library(tidyverse)
2015-07-29 00:16:58 +08:00
```
2022-02-23 07:48:09 +08:00
From this chapter on, we'll suppress the loading message from `library(tidyverse)`.
2015-07-29 03:15:28 +08:00
## Tidy data
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
You can represent the same underlying data in multiple ways.
The example below shows the same data organised in four different ways.
2022-02-24 07:17:19 +08:00
Each dataset shows the same values of four variables *country*, *year*, *population*, and *cases*, but each dataset organizes the values in a different way.
2015-07-29 00:16:58 +08:00
```{r}
table1
table2
table3
2016-07-26 00:28:05 +08:00
# Spread across two tibbles
2021-02-06 00:44:17 +08:00
table4a # cases
table4b # population
2015-07-29 00:16:58 +08:00
```
2021-02-21 23:40:40 +08:00
These are all representations of the same underlying data, but they are not equally easy to use.
One dataset, the tidy dataset, will be much easier to work with inside the tidyverse.
2016-08-12 21:58:32 +08:00
There are three interrelated rules which make a dataset tidy:
2015-07-29 00:16:58 +08:00
2022-02-24 07:17:19 +08:00
1. Each variable is a column; each column is a variable.
2. Each observation is row; each row is an observation
3. Each value is a cell; each cell is a single value.
2016-08-12 21:58:32 +08:00
2022-02-24 07:17:19 +08:00
These three rules are interrelated because typically by fixing one of them you'll fix the other two.
2016-08-12 21:58:32 +08:00
Figure \@ref(fig:tidy-structure) shows the rules visually.
2022-02-24 07:17:19 +08:00
In the example above, only `table1` is tidy.
```{r tidy-structure, echo = FALSE, out.width = "100%"}
#| fig.cap: >
#| Following three rules makes a dataset tidy: variables are columns,
#| observations are rows, and values are cells.
#| fig.alt: >
#| Three panels, each representing a tidy data frame. The first panel
#| shows that each variable is column. The second panel shows that each
#| observation is a row. The third panel shows that each value is
#| a cell.
2015-12-12 03:28:10 +08:00
knitr::include_graphics("images/tidy-1.png")
```
2021-02-21 23:40:40 +08:00
Why ensure that your data is tidy?
There are two main advantages:
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
1. There's a general advantage to picking one consistent way of storing data.
If you have a consistent data structure, it's easier to learn the tools that work with it because they have an underlying uniformity.
2016-07-27 06:44:17 +08:00
2021-02-21 23:40:40 +08:00
2. There's a specific advantage to placing variables in columns because it allows R's vectorised nature to shine.
As you learned in Sections \@ref(mutate-funs) and \@ref(summarise-funs), most built-in R functions work with vectors of values.
That makes transforming tidy data feel particularly natural.
dplyr, ggplot2, and all the other packages in the tidyverse are designed to work with tidy data.
Here are a couple of small examples showing how you might work with `table1`.
2015-07-29 00:16:58 +08:00
2022-02-24 07:17:19 +08:00
```{r fig.width = 5}
#| fig.alt: >
#| This figure shows the numbers of cases in 1999 and 2000 for
#| Afghanistan, Brazil, and China, with year on the x-axis and number
#| of cases on the y-axis. Each point on the plot represents the number
#| of cases in a given country in a given year. The points for each
#| country are differentiated from others by color and shape and connected
#| with a line, resulting in three, non-parallel, non-intersecting lines.
#| The numbers of cases in China are highest for both 1999 and 2000, with
#| values above 200,000 for both years. The number of cases in Brazil is
#| approximately 40,000 in 1999 and approximately 75,000 in 2000. The
#| numbers of cases in Afghanistan are lowest for both 1999 and 2000, with
#| values that appear to be very close to 0 on this scale.
2016-08-12 21:58:32 +08:00
# Compute rate per 10,000
2022-02-24 03:15:52 +08:00
table1 |>
2022-02-24 07:17:19 +08:00
mutate(
rate = cases / population * 10000
)
2015-07-29 00:16:58 +08:00
2016-07-26 00:28:05 +08:00
# Compute cases per year
2022-02-24 03:15:52 +08:00
table1 |>
2016-07-26 00:28:05 +08:00
count(year, wt = cases)
2015-07-29 00:16:58 +08:00
2016-07-26 00:28:05 +08:00
# Visualise changes over time
2021-02-06 00:44:17 +08:00
ggplot(table1, aes(year, cases)) +
geom_line(aes(group = country), colour = "grey50") +
geom_point(aes(colour = country, shape = country)) +
scale_x_continuous(breaks = c(1999, 2000))
2015-07-29 00:16:58 +08:00
```
2016-07-26 00:28:05 +08:00
### Exercises
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
1. Using prose, describe how the variables and observations are organised in each of the sample tables.
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
2. Compute the `rate` for `table2`, and `table4a` + `table4b`.
2016-07-26 00:28:05 +08:00
You will need to perform four operations:
2015-07-29 00:16:58 +08:00
2021-02-06 00:44:17 +08:00
a. Extract the number of TB cases per country per year.
2021-02-21 23:40:40 +08:00
b. Extract the matching population per country per year.
c. Divide cases by population, and multiply by 10000.
d. Store back in the appropriate place.
Which representation is easiest to work with?
Which is hardest?
Why?
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
3. Recreate the plot showing change in cases over time using `table2` instead of `table1`.
What do you need to do first?
2015-07-29 00:16:58 +08:00
2020-01-16 00:17:10 +08:00
## Pivoting
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
The principles of tidy data seem so obvious that you might wonder if you'll ever encounter a dataset that isn't tidy.
Unfortunately, however, most data that you will encounter will be untidy.
There are two main reasons:
1. Most people aren't familiar with the principles of tidy data, and it's hard to derive them yourself unless you spend a *lot* of time working with data.
2016-07-27 21:23:28 +08:00
2022-02-24 07:17:19 +08:00
2. Data is often organised to facilitate some goal other than analysis.
For example, data is often organised to make collection as easy as possible.
2021-02-21 23:40:40 +08:00
This means for most real analyses, you'll need to do some tidying.
The first step is always to figure out what the variables and observations are.
Sometimes this is easy; other times you'll need to consult with the people who originally generated the data.
2016-08-12 21:58:32 +08:00
The second step is to resolve one of two common problems:
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
1. One variable might be spread across multiple columns.
2016-07-27 21:23:28 +08:00
2021-02-21 23:40:40 +08:00
2. One observation might be scattered across multiple rows.
2016-07-27 21:23:28 +08:00
2021-02-21 23:40:40 +08:00
To fix these problems, you'll need the two most important functions in tidyr: `pivot_longer()` and `pivot_wider()`.
2022-02-24 07:17:19 +08:00
As you might guess from their names these functions are complements: `pivot_longer()` makes wide tables narrower and longer; `pivot_wider()` makes long tables shorter and wider.
Typically a dataset will only suffer from one of these problems; it'll only suffer from both if you're really unlucky!
2016-01-29 05:10:04 +08:00
2020-01-16 00:17:10 +08:00
### Longer
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
A common problem is a dataset where some of the column names are not names of variables, but *values* of a variable.
Suppose you have your data in the following format.
2015-07-29 00:16:58 +08:00
```{r}
2016-07-27 06:44:17 +08:00
table4a
2015-07-29 00:16:58 +08:00
```
2021-02-06 00:44:17 +08:00
And you want to create the following visualisation where each line represents a `country`, `year` is on the x-axis, `cases` are on the y-axis, and you automatically get the legend that indicates which line represents which country.
2022-02-24 07:17:19 +08:00
```{r tidy-pivot-longer-plot-lines, fig.width = 5, echo = FALSE}
#| fig.cap: >
#| Number of cases over the years for each country.
#| fig.alt: >
#| This figure shows the numbers of cases in 1999 and 2000 for
#| Afghanistan, Brazil, and China, with year on the x-axis and number of
#| cases on the y-axis. Each point on the plot represents the number of
#| cases in a given country in a given year. The points for each country
#| are differentiated from others by color and shape and connected with a
#| line, resulting in three, non-parallel, non-intersecting lines. The
#| numbers of cases in China are highest for both 1999 and 2000, with values above 200,000 for both years. The number of cases in Brazil is approximately 40,000 in 1999 and approximately 75,000 in 2000. The numbers of cases in Afghanistan are lowest for both 1999 and 2000, with values that appear to be very close to 0 on this scale."
2022-02-24 03:15:52 +08:00
table4a |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = c(`1999`, `2000`),
names_to = "year",
values_to = "cases",
2022-02-24 03:15:52 +08:00
) |>
mutate(year = parse_integer(year)) |>
2021-02-06 00:44:17 +08:00
ggplot(aes(x = year, y = cases)) +
geom_line(aes(group = country), colour = "grey50") +
geom_point(aes(colour = country, shape = country)) +
scale_x_continuous(breaks = c(1999, 2000))
```
2022-02-24 07:17:19 +08:00
It's most straightforward to do this starting with a data frame where `country`, `year`, and `cases` are the columns and each row represents a record from a country for a particular year.
Something like the following:
2021-02-06 00:44:17 +08:00
2022-02-24 07:17:19 +08:00
```{r}
table1 |> select(country, year, cases)
2021-02-06 00:44:17 +08:00
```
However in `table4a` the column names `1999` and `2000` represent values of the `year` variable, the values in the `1999` and `2000` columns represent values of the `cases` variable, and each row represents two observations, not one.
2021-02-21 23:40:40 +08:00
To tidy a dataset like this, we need to **pivot** the offending columns into a new pair of variables.
To describe that operation we need three parameters:
- The set of columns whose names are values, not variables.
In this example, those are the columns `1999` and `2000`.
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
- The name of the variable to move the column names to: `year`.
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
- The name of the variable to move the column values to: `cases`.
2015-07-29 00:16:58 +08:00
2020-01-16 00:17:10 +08:00
Together those parameters generate the call to `pivot_longer()`:
2015-07-29 00:16:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
table4a |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = c(`1999`, `2000`),
names_to = "year",
values_to = "cases"
)
2015-07-29 00:16:58 +08:00
```
2022-02-24 07:17:19 +08:00
The `cols` argument specifies the columns to pivot using `dplyr::select()` style notation.
2021-02-21 23:40:40 +08:00
Here there are only two columns, so we list them individually.
2022-02-24 07:17:19 +08:00
Unfortunately, there's a challenge!
`1999` and `2000` are unusual column names.
Because they don't start with a letter they're called **non-syntactic** names and we have to surround them in backticks.
2021-02-21 23:40:40 +08:00
To refresh your memory of the other ways to select columns, see Section \@ref(select).
2021-02-06 00:44:17 +08:00
`year` and `cases` do not exist in `table4a` so we put their names in quotes in `names_to` and `values_to` arguments, respectively.
2016-07-27 06:44:17 +08:00
2021-02-21 23:40:40 +08:00
In the final result, the pivoted columns are dropped, and we get new `year` and `cases` columns.
Otherwise, the relationships between the original variables are preserved.
Visually, this is shown in Figure \@ref(fig:tidy-pivot-longer).
2020-01-16 00:17:10 +08:00
2022-02-24 07:17:19 +08:00
```{r tidy-pivot-longer, echo = FALSE, out.width = "100%"}
#| fig.cap: >
#| Pivoting `table4a` into a "longer", tidy form.
#| fig.alt: >
#| Two panels, one with a longer and the other with a wider data frame.
#| Arrows represent how values in the 1999 and 2000 columns of the wider
#| data frame are pivoted to a column named cases in the longer data frame
#| and how column names from the wider data frame (1999 and 2000) are
#| pivoted into column names in the longer data frame.
2016-07-27 06:44:17 +08:00
knitr::include_graphics("images/tidy-9.png")
2015-12-12 03:28:10 +08:00
```
2021-02-21 23:40:40 +08:00
There is still one issue though.
Take a peek at the type of the `year` variable.
We would expect `year` to be numeric (or specifically, we would expect it to be an integer), however it's showing up as a character.
This is because the values in the `year` variable came from column headings in `table4a`.
We can add a new step to our pipeline using `dplyr::mutate()` to parse this variable as an integer with `readr::parse_integer()`.
You can refer back to Section \@ref(parsing-a-vector) for functions for parsing other types of vectors.
2021-02-06 00:44:17 +08:00
```{r}
2022-02-24 03:15:52 +08:00
table4a |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = c(`1999`, `2000`),
names_to = "year",
values_to = "cases"
2022-02-24 03:15:52 +08:00
) |>
2021-02-06 00:44:17 +08:00
mutate(year = parse_integer(year))
```
2022-02-24 07:17:19 +08:00
Once we have our data in this longer format, we can create the visualisation that motivated this tidying exercise with the following code.
2020-01-16 00:17:10 +08:00
2022-02-24 07:17:19 +08:00
```{r ref.label = "tidy-pivot-longer-plot-lines", fig.show='hide'}
2021-02-06 00:44:17 +08:00
```
2021-02-21 23:40:40 +08:00
`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.
2020-01-16 00:17:10 +08:00
2021-02-21 23:40:40 +08:00
We can use `pivot_longer()` to tidy `table4b` in a similar fashion.
The only difference is the variable stored in the cell values:
2015-07-29 00:16:58 +08:00
2016-07-26 00:28:05 +08:00
```{r}
2022-02-24 03:15:52 +08:00
table4b |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = c(`1999`, `2000`),
names_to = "year",
values_to = "population"
2022-02-24 03:15:52 +08:00
) |>
2021-02-06 00:44:17 +08:00
mutate(year = parse_integer(year))
2016-07-26 00:28:05 +08:00
```
2015-07-29 00:16:58 +08:00
2021-02-06 00:44:17 +08:00
To combine the tidied versions of `table4a` and `table4b` into a single tibble, we need to use `dplyr::left_join()`, which you'll learn about in Chapter \@ref(relational-data).
2015-07-29 00:16:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
tidy4a <- table4b |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = c(`1999`, `2000`),
names_to = "year",
values_to = "cases"
2022-02-24 03:15:52 +08:00
) |>
2021-02-06 00:44:17 +08:00
mutate(year = parse_integer(year))
2022-02-24 03:15:52 +08:00
tidy4b <- table4b |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = c(`1999`, `2000`),
names_to = "year",
values_to = "population"
2022-02-24 03:15:52 +08:00
) |>
2021-02-06 00:44:17 +08:00
mutate(year = parse_integer(year))
2016-07-27 06:44:17 +08:00
left_join(tidy4a, tidy4b)
2015-07-29 00:16:58 +08:00
```
2020-01-16 00:17:10 +08:00
### Wider
2016-07-27 06:44:17 +08:00
2021-02-21 23:40:40 +08:00
`pivot_wider()` is the opposite of `pivot_longer()`.
You use it when an observation is scattered across multiple rows.
For example, take `table2`: an observation is a country in a year, but each observation is spread across two rows.
2015-07-29 00:16:58 +08:00
```{r}
2016-07-27 06:44:17 +08:00
table2
2015-07-29 00:16:58 +08:00
```
2021-02-06 00:44:17 +08:00
Suppose you'd like to calculate the `rate` (number of `cases` divided by `population`) for each country in a given year, and record it as a new column, resulting in the following data frame.
```{r tidy-pivot-wider-case-ratio, echo = FALSE}
2022-02-24 03:15:52 +08:00
table2 |>
pivot_wider(names_from = type, values_from = count) |>
2021-02-06 00:44:17 +08:00
mutate(rate = cases / population)
```
2021-02-21 23:40:40 +08:00
This means we need a data frame with `cases` and `population` as separate columns, and in those columns, each cell will hold the values of the relevant `count`s.
Let's analyse the representation in similar way to `pivot_longer()`.
This time, however, we only need two parameters:
2016-07-27 21:23:28 +08:00
2021-02-21 23:40:40 +08:00
- The column to take variable names from: `type`.
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
- The column to take values from: `count`.
2015-07-29 00:16:58 +08:00
2021-02-06 00:44:17 +08:00
We can use `pivot_wider()`, as shown programmatically below, and visually in Figure \@ref(fig:tidy-pivot-wider).
2016-07-27 06:44:17 +08:00
```{r}
2022-02-24 03:15:52 +08:00
table2 |>
2021-02-06 00:44:17 +08:00
pivot_wider(names_from = type, values_from = count)
2015-12-12 03:28:10 +08:00
```
2015-07-29 00:16:58 +08:00
2022-02-24 07:17:19 +08:00
```{r tidy-pivot-wider, echo = FALSE, out.width = "100%"}
#| fig.cap: >
#| Pivoting `table2` into a "wider", tidy form.
#| fig.alt: >
#| Two panels, one with a longer and the other with a wider data frame.
#| Arrows represent how values in the count column of the longer data
#| frame are pivoted to two columns named cases and population in the
#| wider data frame as well as how values in the type column of the longer
#| data (cases and population) frame are pivoted into column names in
#| the wider data frame.
2016-07-27 06:44:17 +08:00
knitr::include_graphics("images/tidy-8.png")
2015-07-29 00:16:58 +08:00
```
2021-02-06 00:44:17 +08:00
Once we have our data in this wider format, we can create the data frame that motivated this tidying exercise as follows.
```{r ref.label = "tidy-pivot-wider-case-ratio"}
```
Earlier we visualised case counts over the years, and this representation can be useful for visualising case rates, for example.
2022-02-24 07:17:19 +08:00
```{r}
#| fig.alt: >
#| This figure shows the case rate in 1999 and 2000 for Afghanistan,
#| Brazil, and China, with year on the x-axis and number of cases on the
#| y-axis. Each point on the plot represents the case rate in a given
#| country in a given year. The points for each country are differentiated
#| from others by color and shape and connected with a line, resulting in
#| three, non-parallel, non-intersecting lines. The case rates in Brazil
#| are highest for both 1999 and 2000; approximately 0.0002 in 1999 and
#| approximately 0.00045 in 2000. The case rates in China are slightly
#| below 0.0002 in both 1999 and 2000. The case rates in Afghanistan are
#| lowest for both 1999 and 2000; pretty close to 0 in 1999 and
#| approximately 0.0001 in 2000."
2022-02-24 03:15:52 +08:00
table2 |>
pivot_wider(names_from = type, values_from = count) |>
mutate(rate = cases / population) |>
2021-02-06 00:44:17 +08:00
ggplot(aes(x = year, y = rate)) +
geom_line(aes(group = country), colour = "grey50") +
geom_point(aes(colour = country, shape = country)) +
scale_x_continuous(breaks = c(1999, 2000))
```
Now let's go one step further and widen the data to record `cases`, `population`, and `rate` for 1999 and 2000 in separate columns, such as the following.
```{r tidy-pivot-even-wider-case-ratio, echo = FALSE}
2022-02-24 03:15:52 +08:00
table2 |>
2022-02-24 07:17:19 +08:00
pivot_wider(
names_from = type,
values_from = count
) |>
2022-02-24 03:15:52 +08:00
mutate(rate = cases / population) |>
2021-02-06 00:44:17 +08:00
pivot_wider(
names_from = year,
2022-02-24 07:17:19 +08:00
values_from = c(cases, population, rate),
names_vary = "slowest"
)
2021-02-06 00:44:17 +08:00
```
2021-02-21 23:40:40 +08:00
This representation is rarely useful for data analysis but it might be useful as the basis of a table for communication of results in a data analysis report.
2021-02-06 00:44:17 +08:00
2021-02-21 23:40:40 +08:00
To achieve this we need to add year information in column headings for `cases`, `population`, and `rate` as well as distribute the values that are currently under these three columns into six columns (two columns for each year we have data for).
This is represented in Figure \@ref(fig:tidy-pivot-even-wider).
2021-02-06 00:44:17 +08:00
2022-02-24 07:17:19 +08:00
```{r tidy-pivot-even-wider, echo = FALSE, out.width = "100%"}
#| fig.cap: >
#| Pivoting `table2` into an even "wider" form. Arrows for `cases` and
#| `rate` values are omitted for clarity.
#| fig.alt: >
#| Two panels, one with a wider and the other with an even wider data
#| frame. Arrows represent how population values for 1999 and 2000 that
#| are stored in a single column in the wide data frame are spread across
#| two columns in the data frame that is even wider. These new columns
#| are called population_1999 and population_2000.
2021-02-06 00:44:17 +08:00
knitr::include_graphics("images/tidy-19.png")
```
2021-02-21 23:40:40 +08:00
To do so, we'll take advantage of the fact that the pivot functions can operate on multiple columns at once.
The first three lines of the following code chunk is what we've already done in the previous step and we add on to the pipeline another `pivot_wider()` step where the values for the added columns come from `cases`, `population`, and `rate` and the column names are automatically suffixed with values from the `year` variable.
2021-02-06 00:44:17 +08:00
```{r}
2022-02-24 03:15:52 +08:00
table2 |>
2022-02-24 07:17:19 +08:00
pivot_wider(
names_from = type,
values_from = count
) |>
2022-02-24 03:15:52 +08:00
mutate(rate = cases / population) |>
2021-02-06 00:44:17 +08:00
pivot_wider(
names_from = year,
2022-02-24 07:17:19 +08:00
values_from = c(cases, population, rate),
names_vary = "slowest"
2021-02-06 00:44:17 +08:00
)
```
2022-02-24 07:17:19 +08:00
Note the use of `names_vary` to keep the years (coming from the columns names) together.
2021-02-06 00:44:17 +08:00
```{r ref.label = "tidy-pivot-even-wider-case-ratio"}
```
2016-07-26 00:28:05 +08:00
### Exercises
2021-02-21 23:40:40 +08:00
1. Why are `pivot_longer()` and `pivot_wider()` not perfectly symmetrical?\
2016-07-26 00:28:05 +08:00
Carefully consider the following example:
2021-02-21 23:40:40 +08:00
2016-07-26 00:28:05 +08:00
```{r, eval = FALSE}
2016-10-04 03:10:05 +08:00
stocks <- tibble(
2016-07-26 00:28:05 +08:00
year = c(2015, 2015, 2016, 2016),
2021-02-06 00:44:17 +08:00
half = c( 1, 2, 1, 2),
2016-07-26 00:28:05 +08:00
return = c(1.88, 0.59, 0.92, 0.17)
)
2022-02-24 03:15:52 +08:00
stocks |>
pivot_wider(names_from = year, values_from = return) |>
2020-01-16 00:17:10 +08:00
pivot_longer(`2015`:`2016`, names_to = "year", values_to = "return")
2016-07-26 00:28:05 +08:00
```
2021-02-21 23:40:40 +08:00
(Hint: look at the variable types and think about column *names*.)
`pivot_longer()` has a `names_ptypes` argument, e.g. `names_ptypes = list(year = double())`.
What does it do?
2. Why does this code fail?
2016-07-27 06:44:17 +08:00
```{r, error = TRUE}
2022-02-24 03:15:52 +08:00
table4a |>
2020-01-16 00:17:10 +08:00
pivot_longer(c(1999, 2000), names_to = "year", values_to = "cases")
2016-07-27 06:44:17 +08:00
```
2021-02-21 23:40:40 +08:00
3. What would happen if you widen this table?
Why?
How could you add a new column to uniquely identify each value?
2016-07-26 00:28:05 +08:00
```{r}
2016-10-04 03:10:05 +08:00
people <- tribble(
2020-01-16 00:17:10 +08:00
~name, ~names, ~values,
2021-02-06 00:44:17 +08:00
#-----------------|--------|-------
"Phillip Woods", "age", 45,
"Phillip Woods", "height", 186,
"Phillip Woods", "age", 50,
"Jessica Cordero", "age", 37,
"Jessica Cordero", "height", 156
2016-07-26 00:28:05 +08:00
)
```
2021-02-21 23:40:40 +08:00
4. The simple tibble below summarizes information on whether employees at a small company know how to drive and whether they prefer a position where they will need to drive daily for sales calls.
Tidy the table to get it into a format where each observation is an employee.
Do you need to make it wider or longer?
What are the variables?
2016-07-26 00:28:05 +08:00
```{r}
2021-02-06 00:44:17 +08:00
employees <- tribble(
~know_drive, ~prefer, ~not_prefer,
"yes", 20, 10,
"no", NA, 12
2016-07-26 00:28:05 +08:00
)
```
2021-02-21 23:40:40 +08:00
5. One way of summarising the distribution of one categorical variable based on the levels of another is using `dplyr::count()`, e.g. the following gives the distribution of `drv` (type of drive train) for each level of `cyl` (number of cylinders) for cars in the `mpg` dataset.
2021-02-06 00:44:17 +08:00
```{r}
2022-02-24 03:15:52 +08:00
mpg |>
2021-02-06 00:44:17 +08:00
count(cyl, drv)
```
2021-02-21 23:40:40 +08:00
A contingency table is another way commonly used way of summarising this information.
Use one of the pivoting functions to construct the contingency table shown below based on the output above.
2021-02-06 00:44:17 +08:00
```{r echo = FALSE}
2022-02-24 03:15:52 +08:00
mpg |>
count(cyl, drv) |>
2021-02-06 00:44:17 +08:00
pivot_wider(names_from = drv, values_from = n)
```
## Case study
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
To finish off the chapter, let's pull together everything you've learned to tackle a realistic data tidying problem.
The `tidyr::who` dataset contains tuberculosis (TB) cases broken down by year, country, age, gender, and diagnosis method.
The data comes from the *2014 World Health Organization Global Tuberculosis Report*, available at <http://www.who.int/tb/country/data/download/en>.
2016-07-27 06:44:17 +08:00
There's a wealth of epidemiological information in this dataset, but it's challenging to work with the data in the form that it's provided:
2015-07-29 00:16:58 +08:00
2015-07-29 03:15:28 +08:00
```{r}
2015-07-29 00:16:58 +08:00
who
```
2021-02-21 23:40:40 +08:00
This is a very typical real-life example dataset.
It contains redundant columns, odd variable names, and many missing values.
In short, the `who` dataset is messy, and we'll need to be methodical about how we tidy it.
With functions like `pivot_wider()` and `pivot_longer()` this generally means an iterative approach will work well -- aim to accomplish one goal at a time, run the function and examine the resulting data frame, then go back and set more arguments of the function as needed until the resulting data frame is exactly what you need.
2021-02-06 00:44:17 +08:00
The best place to start is to take a good look at the variable names and determine whether they are actually variables or if they contain information that should be captured as values in a new column.
```{r}
names(who)
```
2016-07-27 06:44:17 +08:00
2021-02-21 23:40:40 +08:00
- It looks like `country`, `iso2`, and `iso3` are three variables that redundantly specify the country.
- `year` is also a variable.
- The first three letters of the variables `new_sp_m014` through `newrel_f65` denote whether the column contains new or old cases of TB.
In this dataset, each column contains new cases, so we don't really need this information to be captured in a variable.
The remaining characters in encode three variables in their names.
You might be able to parse this out by yourself with a little thought and some experimentation, but luckily we have the data dictionary handy.
It tells us:
2016-07-27 06:44:17 +08:00
2021-02-21 23:40:40 +08:00
1. The next two or three letters describe the diagnosis of TB:
2021-02-06 00:44:17 +08:00
2021-02-21 23:40:40 +08:00
- `rel` stands for cases of relapse
- `ep` stands for cases of extrapulmonary TB
- `sn` stands for cases of pulmonary TB that could not be diagnosed by a pulmonary smear (smear negative)
- `sp` stands for cases of pulmonary TB that could be diagnosed by a pulmonary smear (smear positive)
2021-02-06 00:44:17 +08:00
2021-02-21 23:40:40 +08:00
2. The next letter gives the sex of TB patients.
The dataset groups cases by males (`m`) and females (`f`).
2021-02-06 00:44:17 +08:00
2021-03-26 21:12:18 +08:00
3. The remaining numbers give the age group.
2021-02-21 23:40:40 +08:00
The dataset groups cases into seven age groups:
2021-02-06 00:44:17 +08:00
2021-02-21 23:40:40 +08:00
- `014` = 0 -- 14 years old
- `1524` = 15 -- 24 years old
- `2534` = 25 -- 34 years old
- `3544` = 35 -- 44 years old
- `4554` = 45 -- 54 years old
- `5564` = 55 -- 64 years old
- `65` = 65 or older
2021-02-06 00:44:17 +08:00
2021-02-21 23:40:40 +08:00
We can break these variables up by specifying multiple column names in `names_to` and then either providing `names_pattern` to specify how we want to break them up with a regular expression containing groups (defined by `()`) and it puts each group in a column.
You'll learn more about regular expressions in Chapter \@ref(strings), but the basic idea is that in a variable name like `new_sp_m014`, we want to capture `sp`, `m`, and `014` as separate groups, so we can think about this variable's name as `new_(sp)_(m)(014)`.
In constructing the appropriate regular expression we need to keep in mind a few messy features of these variable names:
2021-02-06 00:44:17 +08:00
2021-02-21 23:40:40 +08:00
- Some of the variables start with `new_` while some of them start with `new` without an underscore separating it from the diagnosis.
- The diagnoses and the age groups are indicated by varying numbers of characters (e.g. `sp` vs. `rel` and `014` vs. `4554`.)
2021-02-06 00:44:17 +08:00
The regular expression that will capture all of these inconsistencies and extract the three groups of information we need is `new_?(.*)_(.)(.*)`.
2016-07-27 06:44:17 +08:00
```{r}
2022-02-24 03:15:52 +08:00
who |>
2020-01-16 00:17:10 +08:00
pivot_longer(
2021-02-06 00:44:17 +08:00
cols = new_sp_m014:newrel_f65,
names_to = c("diagnosis", "gender", "age"),
names_pattern = "new_?(.*)_(.)(.*)",
values_to = "cases"
2020-01-16 00:17:10 +08:00
)
2016-07-27 06:44:17 +08:00
```
2021-02-21 23:40:40 +08:00
This looks pretty good for a first pass, but there are some improvements we can make.
First, we're seeing lots of `NA`s in the `cases` column.
We can drop these observations by setting `values_drop_na` to `TRUE`.
2016-07-27 06:44:17 +08:00
```{r}
2022-02-24 03:15:52 +08:00
who |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = c("diagnosis", "gender", "age"),
names_pattern = "new_?(.*)_(.)(.*)",
values_to = "cases",
values_drop_na = TRUE
)
2016-07-26 00:28:05 +08:00
```
2015-07-29 00:16:58 +08:00
2021-02-21 23:40:40 +08:00
Second, `diagnosis` and `gender` are characters by default, however it's a good idea to convert them to factors since they are categorical variables with a known set of values.
We'll use the `parse_factor()` function from readr to make the conversion in a `mutate()` step we add to the pipeline.
2015-07-29 00:16:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
who |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = c("diagnosis", "gender", "age"),
names_pattern = "new_?(.*)_(.)(.*)",
values_to = "cases",
values_drop_na = TRUE
2022-02-24 03:15:52 +08:00
) |>
2021-02-06 00:44:17 +08:00
mutate(
gender = parse_factor(gender, levels = c("f", "m")),
age = parse_factor(
age,
levels = c("014", "1524", "2534", "3544", "4554", "5564", "65"),
ordered = TRUE
)
)
2015-07-29 00:16:58 +08:00
```
2021-02-21 23:40:40 +08:00
Finally, we might want to recode the `age` variable with level names that are a bit easier to read and a bit more informative.
We'll do this within the `mutate()` step of our pipeline using `forcats::fct_recode()` that you'll learn more about in Chapter \@ref(factors).
2015-07-29 00:16:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
who_tidy <- who |>
2021-02-06 00:44:17 +08:00
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = c("diagnosis", "gender", "age"),
names_pattern = "new_?(.*)_(.)(.*)",
values_to = "cases",
values_drop_na = TRUE
2022-02-24 03:15:52 +08:00
) |>
2021-02-06 00:44:17 +08:00
mutate(
gender = parse_factor(gender, levels = c("f", "m")),
age = parse_factor(
age,
levels = c("014", "1524", "2534", "3544", "4554", "5564", "65"),
ordered = TRUE
),
age = fct_recode(
age,
"0-14" = "014",
"15-24" = "1524",
"25-34" = "2534",
"35-44" = "3544",
"45-54" = "4554",
"55-64" = "5564",
"65+" = "65"
)
)
who_tidy
2015-07-29 00:16:58 +08:00
```
2021-02-21 23:40:40 +08:00
This tidy data frame allows us to explore the data with more ease than the original `who` dataset.
For example, we can easily filter for a particular type of TB for a given country and sum over the number of cases to see how case numbers for this type of TB have evolved over the years.
2015-07-29 00:16:58 +08:00
2022-02-24 07:17:19 +08:00
```{r}
#| fig.alt: >
#| A scatterplot of number of smear positive pulmonary TB cases in the
#| US over the years, with year on the x-axis ranging from 1995 to 2013
#| and yearly total number of cases on the y-axis ranging from 3000 to
#| 8000. The points on the scatterplot are overlaid with a smooth curve,
#| which shows a strong, negative association between the two variables.
2022-02-24 03:15:52 +08:00
who_tidy |>
filter(diagnosis == "sp", country == "United States of America") |>
group_by(year) |>
summarise(cases_total = sum(cases)) |>
2021-02-06 00:44:17 +08:00
ggplot(aes(x = year, y = cases_total)) +
geom_point() +
geom_smooth() +
labs(title = "Number of smear positive pulmonary TB cases in the US")
2015-07-29 00:16:58 +08:00
```
2016-07-26 00:28:05 +08:00
### Exercises
2021-02-21 23:40:40 +08:00
1. In this case study I set `values_drop_na = TRUE` just to make it easier to check that we had the correct values.
Is this reasonable?
Think about how missing values are represented in this dataset.
Are there implicit missing values?
What's the difference between an `NA` and zero?
2016-07-26 00:28:05 +08:00
2021-02-21 23:40:40 +08:00
2. I claimed that `iso2` and `iso3` were redundant with `country`.
Confirm this claim and think about situations where we might want to keep this information in the data frame and when we might choose to discard the redundant columns.
2016-07-26 00:28:05 +08:00
2021-02-21 23:40:40 +08:00
3. For each country, year, and sex compute the total number of cases of TB.
Make an informative visualisation of the data.
2016-07-26 00:28:05 +08:00
## Non-tidy data
2021-02-21 23:40:40 +08:00
Before we continue on to other topics, it's worth talking briefly about non-tidy data.
Earlier in the chapter, I used the pejorative term "messy" to refer to non-tidy data.
That's an oversimplification: there are lots of useful and well-founded data structures that are not tidy data.
There are two main reasons to use other data structures:
- Alternative representations may have substantial performance or space advantages.
2016-07-26 00:28:05 +08:00
2021-02-21 23:40:40 +08:00
- Specialised fields have evolved their own conventions for storing data that may be quite different to the conventions of tidy data.
2016-07-26 00:28:05 +08:00
2021-02-21 23:40:40 +08:00
Either of these reasons means you'll need something other than a tibble (or data frame).
If your data does fit naturally into a rectangular structure composed of observations and variables, I think tidy data should be your default choice.
But there are good reasons to use other structures; tidy data is not the only way.
2016-07-26 00:28:05 +08:00
2021-12-31 06:38:41 +08:00
If you'd like to learn more about non-tidy data, I'd highly recommend this thoughtful blog post by Jeff Leek: <https://simplystatistics.org/posts/2016-02-17-non-tidy-data>.