Mar 14, 2018
|
17 min
|
68.1k views
Tidy Data in R with tidyr: Reshaping Data the Tidyverse Way (Part 2)
Tidy data means one variable per column, one observation per row, and one value per cell. R is built around element-wise operations on columns, so data in that shape works with the language instead of against it. tidyr is the package that gets you there: gather turns columns into key and value pairs, spread turns key and value pairs back into columns, and unite and separate split or combine the values inside them.
What you will learn
What tidy data is, in three rules you can check a dataset against How to tell a tidy dataset from an untidy one, with worked examples of both Why an untidy layout forces you to write worse code What element-wise operations are, and why they reward a tidy layout How gather works, and what key and value mean How spread reverses it, and when you would want to What unite and separate do to the values inside a column Chapters 0:00 What part 2 covers 0:48 Making your data suitable for R 1:40 What tidy data means, and why it matters 2:12 A dataset that is already tidy 3:18 A dataset that is not 4:24 Why an untidy layout makes your code harder 5:30 Element-wise operations, and why R prefers tidy columns 6:36 The definition of tidy data 7:42 What tidyr does, and its two main functions 8:48 gather: turning columns into key and value pairs 9:54 The vocabulary: key, value and the columns you gather 11:00 Working through a gather call 12:06 From rectangular to tidy 12:30 spread: turning key and value pairs back into columns 14:18 The syntax of spread 15:23 unite and separate 16:30 Recap of the tidyr package
Note on current function names This video uses gather and spread. Current tidyr uses pivot_longer and pivot_wider for the same operations. Both still work. See https://tidyr.tidyverse.org/articles/pivot.html
The rest of the series Part 1, what is data wrangling: https://www.youtube.com/watch?v=jOd65mR1zfw Part 3, dplyr: https://www.youtube.com/watch?v=Zc_ufg4uW4U Part 4, joins and set operations: https://www.youtube.com/watch?v=AuBgYDCg1Cg
Learn more tidyr: https://tidyr.tidyverse.org tidyverse: https://www.tidyverse.org
dplyr
tidyr
tidyverse
tidyverse.org
Tidy Data
Tidyr
What Is Tidy Data
Gather and Spread R
Pivot_longer
Pivot_wider
Reshape Data in R
Tidyverse
Data Wrangling in R
Tibbles
R Data Manipulation
Garrett Grolemund
Posit