dem_score <- read_csv("https://moderndive.com/data/dem_score.csv")with the readr and tidyr packages
reshaping a data frame wide <-> long
read_csv()pivot_longer()pivot_wider()Every tool from the last two chapters assumes your data is tidy.
Three rules. A data frame that follows all three works with every ggplot2 and dplyr function you have already met.
Three Rules
Import a comma-separated values file into R as a data frame. From the readr package, not the base R function of a similar name.
Import a Spreadsheet
read_csv() is not read.csv(): the underscore version is the tidyverse one.
Example
what to call the result
the verb (function) where the file is: a path or a URL
One row per case, with a column for every year or category. Easy to read on a page, awkward to plot: the variable you want on the x-axis is spread across the column names.
Values Hidden In Headers
Turn many columns into two: one holding the old column names, one holding the values. This is what makes a wide table tidy.
Wide To Long
Diagram adapted from Garrick Aden-Buie’s tidyexplain
Example
the data frame
the verb (function) new column for the old headers new column for the values which columns to reshape
The inverse of pivot_longer(). Spread one column of names back out into many columns. Useful for presenting a table, rarely for analysis.
Long To Wide
Diagram adapted from Garrick Aden-Buie’s tidyexplain
Example
the verb (function) column supplying the new headers column supplying the new values
One package that loads the others.
The Umbrella Package