R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
18: Reshaping Data with tidyr
You've probably seen this a thousand times: a spreadsheet where the dates or categories are the column headers. It looks great to a human reading a report, but for R, it's a nightmare. We call this "wide" data. To actually analyze it—filter it, group it, or plot it with ggplot2—we need "long" data, where each row is a single observation.
Let's look at a real-world scenario. I've got some quarterly revenue data for three different product lines. It's currently in a wide format that would make any data scientist cringe.
library(tidyr)
library(dplyr)
# This is how the data usually arrives from a business user
revenue_wide <- data.frame(
product = c("Widget A", "Widget B", "Widget C"),
q1 = c(1200, 1500, 800),
q2 = c(1300, 1400, 900),
q3 = c(1100, 1600, 850),
q4 = c(1500, 1700, 1000)
)
Collapsing the quarters into a single column
I want to move those q1 through q4 columns into a single column called "quarter" and their values into a column called "revenue". This is where pivot_longer() comes in. It's the workhorse of tidyr.
# My first attempt at reshaping
revenue_long <- revenue_wide %>%
pivot_longer(
cols = everything(),
names_to = "quarter",
values_to = "revenue"
)
Correcting the "over-pivot" mistake
If you run the code above, you'll notice something is wrong. I used cols = everything(), which means R pivoted the product column too. Now I have "Widget A" sitting in the "quarter" column, and the actual product name sitting in the "revenue" column. That's a mess.
In pivot_longer, you have to be explicit about which columns should be collapsed. I can either list the columns I want to pivot, or—even better—tell R to pivot everything except the product column using the minus sign.
# The corrected version
revenue_long <- revenue_wide %>%
pivot_longer(
cols = -product,
names_to = "quarter",
values_to = "revenue"
)
print(revenue_long)
Now we have a tidy dataset. Each row is a unique combination of a product and a quarter. This is the format you need if you ever want to use group_by() or create a line chart of revenue over time.
Reorganizing for a custom summary
Sometimes you need to go the other way. Maybe you've done some calculations and you want to create a specific cross-tabulation for a presentation. That's where pivot_wider() fits in. It's essentially the inverse of pivot_longer.
Let's say I've calculated a "performance" flag for each quarter (I'll just simulate some dummy data for this), and I want to see a grid of products vs. quarters showing that flag.
# Adding a dummy performance column
revenue_long <- revenue_long %>%
mutate(status = if_else(revenue > 1300, "High", "Low"))
# Now, let's widen it back out, but using 'status' instead of 'revenue'
status_grid <- revenue_long %>%
select(product, quarter, status) %>%
pivot_wider(
names_from = quarter,
values_from = status
)
print(status_grid)
By using names_from and values_from, I've turned the data back into a wide format, but I've changed the actual content of the cells. This flexibility is why tidyr is so powerful—it's not just about "fixing" data, but about sculpting it into the shape required for the next step of your pipeline.
📋 Practical Task
Normalizing the City Temperature Records
You have been handed a dataset of average monthly temperatures for three cities. The data is currently "wide," with months as columns. This makes it impossible to calculate the annual average temperature per city using a simple group_by.
temp_data <- data.frame(
city = c("New York", "London", "Tokyo"),
Jan = c(3, 5, 6),
Feb = c(4, 6, 7),
Mar = c(8, 9, 10)
)
Your Task: Use pivot_longer() to reshape this data so that it has three columns: city, month, and avg_temp. Ensure that the city column remains as an identifier and is not pivoted into the month column.
There are no comments for now.