Skip to Content
Course content

226: Timed Mock Assessment on Core R and Tidyverse

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Alright, we've spent the last few dozen lessons building up your toolkit. Now, we're at the part I always dread but know is necessary: the timed mock assessment. Instead of just handing you a PDF of questions and saying "good luck," I want to walk you through how I approach these under pressure. I've put together a messy dataset of global coffee production—real-world style, which means it's formatted poorly—and I'm going to set a timer for 20 minutes to extract three specific insights.

Wrestling with the "Wide" Data Trap

First things first. I've got this `coffee_data` frame. Let's see what I'm working with.

# I'll start by peeking at the structure
head(coffee_data)
# Output:
# Country    2020  2021  2022  Region
# Brazil     3500  3200  3800  Americas
# Vietnam    1800  1900  1700  Asia
# Ethiopia    400   420   410  Africa

Immediately, I see the trap. The years are columns. If the assessment asks me to find the average growth rate across all years, I can't do that easily while the data is "wide." I'm tempted to just write a loop, but this is a Tidyverse assessment—I need to be faster. I'll pivot this immediately.

library(tidyverse)

# Attempt 1: Just pivot
coffee_long <- coffee_data %>% 
  pivot_longer(cols = 2:4, names_to = "year", values_to = "production")

head(coffee_long)
# Wait, the 'year' column is a character string now. 
# I can't do math on "2020".

That's a classic mistake. In a timed test, it's easy to forget that `pivot_longer` doesn't automatically know that your column names are actually numbers. I'll fix that on the fly using `mutate`.

coffee_long <- coffee_data %>% 
  pivot_longer(cols = 2:4, names_to = "year", values_to = "production") %>% 
  mutate(year = as.numeric(year))

The Joining Headache

Now, the mock prompt asks for the total production grouped by "Economic Tier" (High, Middle, Low), but that info isn't in my main table. It's in a separate `country_meta` dataframe. Let's try a simple join.

# Trying to merge the data
final_set <- coffee_long %>% 
  left_join(country_meta, by = "Country")

# Checking for NAs
sum(is.na(final_set$economic_tier))
# Output: 12

Twelve NAs? That's a red flag. I know every country in my production list should have a tier. I'll check the original `country_meta` and... there it is. Some countries are listed as "Viet Nam" in the meta-table but "Vietnam" in the production table. This happens constantly in real-world data. I don't have time to manually rename everything, so I'll use `str_replace` to standardize the most common culprit before re-joining.

country_meta <- country_meta %>% 
  mutate(Country = str_replace(Country, "Viet Nam", "Vietnam"))

# Now try the join again
final_set <- coffee_long %>% 
  left_join(country_meta, by = "Country")


Racing the Clock with Aggregation

The final requirement is a summary table showing the year-over-year growth percentage per region. I'm down to my last five minutes. I need to calculate the difference between the current year and the previous year. I'll use `lag()`, but I have to be careful—if I don't group by region first, I'll accidentally subtract Brazil's 2020 production from Ethiopia's 2021 production.

growth_report <- final_set %>% 
  group_by(Region) %>% 
  arrange(year) %>% 
  mutate(prev_prod = lag(production)) %>% 
  mutate(growth = (production - prev_prod) / prev_prod * 100) %>% 
  ungroup()

# Let's see if it worked
filter(growth_report, Region == "Americas")

There it is. The `lag()` function is a lifesaver here. If I had tried to do this with base R indexing, I'd probably still be staring at the screen. By chaining these Tidyverse verbs, I've turned a messy, wide dataset into a clean growth report in under 20 minutes. The key isn't knowing every function perfectly; it's knowing how to pivot, join, and group without getting tangled in the syntax.




📋 Practical Task

Exercise: Cleaning and Analyzing the Brazilian Coffee Export Surge

You have been provided with two dataframes: `export_data` (containing columns `Country`, `2015`, `2016`, `2017`, `2018`, `2019`, and `2020` representing export volumes) and `country_details` (containing `Country` and `Export_Tax_Bracket`).

Write a script to perform the following tasks:

  • Transform the `export_data` from wide format to long format, ensuring the year is stored as an integer.
  • Join the data with `country_details`, handling the case where "Brazil" is misspelled as "Brasil" in the `country_details` table.
  • Calculate the total export volume for each `Export_Tax_Bracket` for the year 2020.
  • Filter the final result to show only brackets that exported more than 1,000,000 units in 2020.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.