1.14 tidyr - Tidy Data

Tidy Data

Stylized text providing an overview of Tidy Data. The top reads “Tidy data is a standard way of mapping the meaning of a dataset to its structure. - Hadley Wickham.” On the left reads “In tidy data: each variable forms a column; each observation forms a row; each cell is a single measurement.” There is an example table on the lower right with columns ‘id’, ‘name’ and ‘color’ with observations for different cats, illustrating tidy data structure.

Messy Data

There are two sets of anthropomorphized data tables. The top group of three tables are all rectangular and smiling, with a shared speech bubble reading “our columns are variables and our rows are observations!”. Text to the left of that group reads “The standard structure of tidy data means that “tidy datasets are all alike…” The lower group of four tables are all different shapes, look ragged and concerned, and have different speech bubbles reading (from left to right) “my column are values and my rows are variables”, “I have variables in columns AND in rows”, “I have multiple variables in a single column”, and “I don’t even KNOW what my deal is.” Next to the frazzled data tables is text “...but every messy dataset is messy in its own way. -Hadley Wickham.”

Messy Data Examples

  • TB cases documented by the WHO in Afghanistan, Brazil, and China, between 1999 and 2000.
  • There are 4 variables: country, year, cases, and population
Table 1
country year cases population
Afghanistan 1999 745 19987071
Afghanistan 2000 2666 20595360
Brazil 1999 37737 172006362
Brazil 2000 80488 174504898
China 1999 212258 1272915272
China 2000 213766 1280428583
  • Each observation is a row
  • Each variable is a column
  • Everything is nicely arranged
  • Easy to compute new variables

Two fuzzballs hold up a tidy data set locked in clamps that say 'wrangle'

Table 2
country year type count
Afghanistan 1999 cases 745
Afghanistan 1999 population 19987071
Afghanistan 2000 cases 2666
Afghanistan 2000 population 20595360
Brazil 1999 cases 37737
Brazil 1999 population 172006362
Brazil 2000 cases 80488
Brazil 2000 population 174504898
China 1999 cases 212258
China 1999 population 1272915272
China 2000 cases 213766
China 2000 population 1280428583
  • type and count contain info for two variables
  • each observation takes up 2 rows
  • easier to plot: separate panels for cases & population with a single command
library(ggplot2)
table2 |> 
  ggplot(aes(x = year, y = count,
             color = country)) +
  geom_line() +
  facet_wrap(~type,
             scales = "free_y")
1
put year on the x-axis, count on the y-axis
2
compute and draw separate shapes (with different colors) for each country
3
draw lines connecting sequential observations
4
create plots for each value of type
5
each plot should have its own y-scale (since cases are much smaller than the population)
Table 3
country year rate
Afghanistan 1999 745/19987071
Afghanistan 2000 2666/20595360
Brazil 1999 37737/172006362
Brazil 2000 80488/174504898
China 1999 212258/1272915272
China 2000 213766/1280428583
  • rate contains cases and population
  • rate isn’t numeric! (we can’t do any math on it in this form)
  • easier to record data in (maybe)?
Table 4a
country 1999 2000
Afghanistan 745 2666
Brazil 37737 80488
China 212258 213766
Table 4b
country 1999 2000
Afghanistan 19987071 20595360
Brazil 172006362 174504898
China 1272915272 1280428583
  • two tables - one for population, one for cases
  • each year’s observation in a separate column
  • often found in Excel (different sheets)
  • Need to make a column for year with the population or case counts, then merge
Table 5
country century year rate
Afghanistan 19 99 745/19987071
Afghanistan 20 00 2666/20595360
Brazil 19 99 37737/172006362
Brazil 20 00 80488/174504898
China 19 99 212258/1272915272
China 20 00 213766/1280428583
  • Excel messes up dates
  • Easier to store Month, Day, Year (maybe Century) separately
  • Combine century and year, split rate as in Table 3

Converting Between Wide and Long Form

Two data tables. The first is labeled 'wide' and has rows id=1, 2 and columns x, y, and z, with values a, b, c, d, e, f in row-first order (so a, b are in column x and rows with id 1, 2 respectively). The second is labeled 'long' and has columns id, key, and value, where id contains 3 replicates of 1, 2, key contains x, x, y, y, z, z, and val contains a, b, c, d, e, f.

An animation that shows the conversion between wide and long form using pivot_wider and pivot_longer commands from tidyr. pivot_wider(data, names_from = key, values_from = val) is used to move from long to wide form, and pivot_longer(data, cols = x:y, names_to = "key", values_to = "val") is used to move from wide to long form.

Images from https://github.com/gadenbuie/tidyexplain

Example: Gas Prices

library(rvest) # <1> scrape data from the web
library(xml2) # <2> parse xml data
library(tidyr)
library(dplyr)
url <- "https://www.eia.gov/dnav/pet/hist/LeafHandler.ashx?n=pet&s=emm_epm0u_pte_nus_dpg&f=w"

htmldoc <- read_html(url)
gas_prices_html <- html_table(htmldoc, fill = T, trim = T)[[5]][,1:11]
head(gas_prices_html, 10)
3
Load tidyr for demonstration
4
Load dplyr to work with data frames
5
Read HTML from the URL
6
Parse the table and convert to a data frame
# A tibble: 10 × 11
   `Year-Month` `Week 1`   `Week 1` `Week 2` `Week 2` `Week 3` `Week 3` `Week 4`
   <chr>        <chr>      <chr>    <chr>    <chr>    <chr>    <chr>    <chr>   
 1 "Year-Month" "End Date" "Value"  "End Da… "Value"  "End Da… "Value"  "End Da…
 2 "1994-Nov"   ""         ""       ""       ""       ""       ""       "11/28" 
 3 "1994-Dec"   "12/05"    "1.143"  "12/12"  "1.118"  "12/19"  "1.099"  "12/26" 
 4 ""           ""         ""       ""       ""       ""       ""       ""      
 5 "1995-Jan"   "01/02"    "1.104"  "01/09"  "1.111"  "01/16"  "1.102"  "01/23" 
 6 "1995-Feb"   "02/06"    "1.103"  "02/13"  "1.099"  "02/20"  "1.093"  "02/27" 
 7 "1995-Mar"   "03/06"    "1.103"  "03/13"  "1.096"  "03/20"  "1.095"  "03/27" 
 8 "1995-Apr"   "04/03"    "1.116"  "04/10"  "1.134"  "04/17"  "1.149"  "04/24" 
 9 "1995-May"   "05/01"    "1.181"  "05/08"  "1.204"  "05/15"  "1.213"  "05/22" 
10 "1995-Jun"   "06/05"    "1.234"  "06/12"  "1.230"  "06/19"  "1.224"  "06/26" 
# ℹ 3 more variables: `Week 4` <chr>, `Week 5` <chr>, `Week 5` <chr>

Sketch

Step 1: set row names to be more descriptive and remove header row. Step 2: Remove empty columns and pivot to long form, with dates and values in the same column and a description column that indicates what type of data is in the value column.

Sketch

Step 3: separate the week and variable information into different columns, discarding the week label. Step 4: pivot wider, so that date and value information are each in a single column.

Sketch

Step 5: remove rows with no values and create a yyyy-mm-dd format date. Step 6: Convert date and value into appropriate types (date, numeric).

Example: Gas Prices

col_names <- c("Year.Month",
               paste("Week",
                     rep(1:5, each = 2),
                     rep(c("Date", "Value"), times = 5), sep = "."))
library(magrittr)

gas_prices_raw <- gas_prices_html |>
  set_names(col_names) |>
  filter(Year.Month != "Year-Month") |>
  filter(Year.Month != "")

head(gas_prices_raw)
1
The first column name is differently structured than the others
2
Create a vector of names that are patterned after the column structure – repeat 1 to 5 with each number twice, e.g. 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, and then repeat Date, Value five times, e.g. Date, Value, Date, Value, …
3
Load the magrittr package, which contains some helpful functions for working with pipes and data - in this case, set_names
4
Set the names of the columns in the data to be col_names
5
Remove the first row that is really an extra header row
6
Get rid of any empty rows.
# A tibble: 6 × 11
  Year.Month Week.1.Date Week.1.Value Week.2.Date Week.2.Value Week.3.Date
  <chr>      <chr>       <chr>        <chr>       <chr>        <chr>      
1 1994-Nov   ""          ""           ""          ""           ""         
2 1994-Dec   "12/05"     "1.143"      "12/12"     "1.118"      "12/19"    
3 1995-Jan   "01/02"     "1.104"      "01/09"     "1.111"      "01/16"    
4 1995-Feb   "02/06"     "1.103"      "02/13"     "1.099"      "02/20"    
5 1995-Mar   "03/06"     "1.103"      "03/13"     "1.096"      "03/20"    
6 1995-Apr   "04/03"     "1.116"      "04/10"     "1.134"      "04/17"    
# ℹ 5 more variables: Week.3.Value <chr>, Week.4.Date <chr>,
#   Week.4.Value <chr>, Week.5.Date <chr>, Week.5.Value <chr>

Example: Gas Prices

gas_prices_long <- pivot_longer(
  gas_prices_raw, 
  -Year.Month,
  names_to = "variable",
  values_to = "value"
)

head(gas_prices_long)
1
We don’t want to change Year.Month at all (yet)
2
We need to keep track of what is a date and what is a value
3
Value information should be kept in a value column. We’ll use it in a bit to pivot into a wider form.
# A tibble: 6 × 3
  Year.Month variable     value
  <chr>      <chr>        <chr>
1 1994-Nov   Week.1.Date  ""   
2 1994-Nov   Week.1.Value ""   
3 1994-Nov   Week.2.Date  ""   
4 1994-Nov   Week.2.Value ""   
5 1994-Nov   Week.3.Date  ""   
6 1994-Nov   Week.3.Value ""   

Example: Gas Prices

gas_prices_long <- gas_prices_long |>
  filter(value != "")

gas_prices_sep <- gas_prices_long |>
  separate(variable, into = c("extra", "week", "variable"), sep = "\\.") |>
  select(-extra) |>
  mutate(week = as.numeric(week))

head(gas_prices_sep)
1
Remove empty rows from gas_prices_long
2
Separate variable into “week”, week number, and “variable” (either “Date” or “Value”)
3
We don’t need a column that only has value “Week”, so get rid of it.
4
Convert week to numeric
# A tibble: 6 × 4
  Year.Month  week variable value
  <chr>      <dbl> <chr>    <chr>
1 1994-Nov       4 Date     11/28
2 1994-Nov       4 Value    1.175
3 1994-Dec       1 Date     12/05
4 1994-Dec       1 Value    1.143
5 1994-Dec       2 Date     12/12
6 1994-Dec       2 Value    1.118

Example: Gas Prices

gas_prices_wide <- pivot_wider(
  gas_prices_sep, 
  id_cols = c("Year.Month", "week"),
  names_from = variable,
  values_from = value)

head(gas_prices_wide)
1
Columns to keep
2
Which column should be used to make new column labels?
3
Which column should be used to fill in the values?
# A tibble: 6 × 4
  Year.Month  week Date  Value
  <chr>      <dbl> <chr> <chr>
1 1994-Nov       4 11/28 1.175
2 1994-Dec       1 12/05 1.143
3 1994-Dec       2 12/12 1.118
4 1994-Dec       3 12/19 1.099
5 1994-Dec       4 12/26 1.088
6 1995-Jan       1 01/02 1.104

Example: Gas Prices

gas_prices_date <- gas_prices_wide |>
  filter(nchar(Value) > 0) |>
  separate(Year.Month, into = c("Year", "Month"), sep = "-") |>
  mutate(Date = paste(Year, Date, sep = "/")) |>
  select(-c(1:3))
  
head(gas_prices_date)
1
Remove any value rows with no characters
2
Split year.month into two columns
3
create a date column with year, month, day
4
Remove redundant information
# A tibble: 6 × 2
  Date       Value
  <chr>      <chr>
1 1994/11/28 1.175
2 1994/12/05 1.143
3 1994/12/12 1.118
4 1994/12/19 1.099
5 1994/12/26 1.088
6 1995/01/02 1.104

Example: Gas Prices

library(lubridate) # Dates and Times -- we will see this next week
library(ggplot2)

gas_prices <- gas_prices_date |>
  mutate(Date = ymd(Date),
         Price.per.gallon = as.numeric(Value)) |>
  select(-Value) 

head(gas_prices)
# A tibble: 6 × 2
  Date       Price.per.gallon
  <date>                <dbl>
1 1994-11-28             1.18
2 1994-12-05             1.14
3 1994-12-12             1.12
4 1994-12-19             1.10
5 1994-12-26             1.09
6 1995-01-02             1.10

Example: Gas Prices

And at the end, we get a nice reward!

ggplot(gas_prices, aes(x = Date, y = Price.per.gallon)) + geom_line()