Hello, young data explorer! In Module 7, we learned how to tell stories with data using pictures and graphs. But before we can make beautiful graphs, we need to make sure our data is clean and ready. Imagine you want to bake a cake – you need to wash the fruits, measure the flour, and mix everything properly. Data is just the same!
In this module, we will learn how to wrangle data. Data wrangling means cleaning, organising, and transforming data so that it is easy to work with. We will use a powerful R package called dplyr. It gives us simple "verbs" – like filter(), select(), mutate(), summarise(), and arrange() – that help us change our data in many useful ways.
By the end of this module, you will be able to take messy data, clean it up, and get it ready for analysis and graphs. You will be a data detective!
dplyr package.filter() to choose rows that meet a condition.select() to choose specific columns.mutate() to create new columns.summarise() to get summary statistics (like mean, sum).arrange() to sort data.%>% to chain commands.Chidi loves helping his mother at the market. One day, his mother gave him a messy list of items to buy:
Chidi was confused. The list had duplicates, the items were not sorted, and he couldn't tell how many of each item he really needed. He decided to clean the list:
Now the list was clear:
Chidi felt proud. He had just wrangled the data! In R, we do the same thing with our datasets – we clean them, combine them, and sort them so we can understand them better.
Definition: Data wrangling is the process of cleaning, transforming, and organising data to make it useful.
Why it is important: Real-world data is often messy – it has mistakes, missing values, or is in the wrong format. Wrangling fixes these issues.
Simple explanation: It's like tidying your room before you can find your toys easily.
Real-life example: A librarian organises books by category and author.
School example: Your teacher sorts test scores from highest to lowest.
Home example: You arrange your clothes by colour in the wardrobe.
Nigerian example: A farmer sorts his harvest by crop type and quality.
Illustration:
Messy Data --> Clean Data --> Ready for Analysis
(duplicates, (no duplicates,
errors, correct format,
unsorted) sorted)
Mini summary: Data wrangling makes data clean and tidy so we can work with it easily.
Definition: dplyr is a popular R package that provides simple functions for data manipulation.
Why it is important: It makes data wrangling fast and easy, with intuitive "verbs" (words that describe actions).
Simple explanation: Think of dplyr as a Swiss Army knife for data – it has many tools in one.
Real-life example: A chef has different knives for cutting, peeling, and slicing – dplyr has different verbs for different tasks.
School example: A pencil case contains a pencil, an eraser, and a ruler – each does a specific job.
Home example: A toolbox has a hammer, a screwdriver, and a wrench.
Nigerian example: A mechanic uses different spanners for different bolts.
Code to install and load:
install.packages("dplyr") # do this once
library(dplyr) # do this every session
Mini summary: dplyr is a toolbox of verbs for cleaning and changing data.
Definition: The pipe operator %>% (pronounced "then") lets you chain multiple operations together in a sequence.
Why it is important: It makes your code easier to read and write, like a recipe with steps.
Simple explanation: It means "and then do this". Instead of writing many nested functions, you write a clear list of actions.
Real-life example: A recipe: "Take eggs, then break them, then whisk them."
School example: "Open your book, then read page 10, then answer the questions."
Home example: "Take the laundry, then put it in the washing machine, then turn it on."
Nigerian example: "Get the yam, then peel it, then cut it, then boil it."
Illustration:
data %>%
filter(...) %>%
select(...) %>%
arrange(...)
# This means: take data, THEN filter, THEN select, THEN arrange.
Mini summary: The pipe %>% helps us chain commands in a logical order.
Definition: filter() picks rows that meet a condition (like "age > 10" or "city == 'Lagos'").
Why it is important: Often we only need a part of the data – e.g., only pupils from a certain class.
Simple explanation: It's like using a sieve to separate big pieces from small pieces.
Real-life example: A shopkeeper filters out expired products.
School example: Your teacher filters the list to only show pupils who scored above 80%.
Home example: You filter your toys to only show the ones you want to give away.
Nigerian example: A researcher filters survey data to only include respondents from Kano.
Code:
library(dplyr)
# Sample data: pupils
pupils <- data.frame(
name = c("Ade", "Bola", "Chidi", "Dami"),
age = c(10, 11, 9, 12),
score = c(85, 70, 90, 65)
)
# Filter to only those with score > 80
pupils %>%
filter(score > 80)
# Result: Ade (85) and Chidi (90)
Before filter: name age score Ade 10 85 Bola 11 70 Chidi 9 90 Dami 12 65 After filter(score > 80): name age score Ade 10 85 Chidi 9 90
Mini summary: filter() keeps only rows that satisfy a condition.
Definition: select() picks specific columns (variables) from your data.
Why it is important: Sometimes we have too many columns and only need a few.
Simple explanation: It's like highlighting important words in a paragraph.
Real-life example: When you read a long article, you focus on the main points.
School example: A teacher might only look at the "name" and "score" columns.
Home example: When you check your phone, you only look at messages, not all apps.
Nigerian example: An economist selects only "State" and "GDP" columns from a big table.
Code:
# Select name and score
pupils %>%
select(name, score)
# Result: only those two columns.
Before select: name age score Ade 10 85 Bola 11 70 After select(name, score): name score Ade 85 Bola 70
Mini summary: select() keeps only the columns you choose.
Definition: mutate() creates a new column (variable) from existing columns, or modifies an existing one.
Why it is important: Often we need to calculate new values, like total or percentage.
Simple explanation: It's like adding a new row to your table with new information.
Real-life example: You calculate your total pocket money by adding your allowance and gifts.
School example: You create a column for "percentage" from test scores.
Home example: You convert minutes into hours and minutes.
Nigerian example: A farmer calculates total harvest in kg by adding different crops.
Code:
# Add a new column: score in percentage (out of 100)
pupils %>%
mutate(percentage = score / 100 * 100) # just score itself, but let's add 10 bonus points
# Actually, let's add bonus: total = score + 5
mutate(total_score = score + 5)
Before mutate: name age score Ade 10 85 After mutate(total_score = score + 5): name age score total_score Ade 10 85 90
Mini summary: mutate() adds new columns by performing calculations.
Definition: summarise() (or summarize()) collapses your data into a single summary row – like mean, sum, count.
Why it is important: It gives you the big picture (e.g., average score, total votes).
Simple explanation: It's like asking "What is the total?" or "What is the average?"
Real-life example: You calculate the total money spent on your shopping trip.
School example: You find the average test score of your class.
Home example: You sum up the minutes you spent on homework each day.
Nigerian example: You summarise the total population of all states.
Code:
# Get average age and average score
pupils %>%
summarise(avg_age = mean(age), avg_score = mean(score))
# Result: one row with the averages.
Before summarise: name age score Ade 10 85 Bola 11 70 Chidi 9 90 Dami 12 65 After summarise(avg_age = mean(age), avg_score = mean(score)): avg_age avg_score 10.5 77.5
Mini summary: summarise() gives you one number or a few numbers that describe your data.
Definition: group_by() splits your data into groups, and then you apply summarise() to each group.
Why it is important: It lets you compare groups (e.g., average score by class).
Simple explanation: It's like sorting your toys by colour and then counting how many of each colour you have.
Real-life example: A shop counts total sales per product category.
School example: Find the average score for each class.
Home example: Count how many hours you spend on each activity (play, study, sleep).
Nigerian example: Calculate the average income per state.
Code:
# Group by age, then get average score per age group
pupils %>%
group_by(age) %>%
summarise(avg_score = mean(score))
Data grouped by age: age avg_score 9 90 10 85 11 70 12 65
Mini summary: group_by() + summarise() gives summaries for each group.
Definition: arrange() sorts your rows by one or more columns, in ascending (default) or descending order.
Why it is important: It helps you see the highest, lowest, or alphabetical order.
Simple explanation: It's like putting your books on a shelf from A to Z.
Real-life example: A teacher sorts pupils' names alphabetically.
School example: You sort test scores from highest to lowest.
Home example: You arrange your clothes from biggest to smallest.
Nigerian example: A business owner sorts sales by highest revenue.
Code:
# Sort by score ascending (lowest to highest)
pupils %>%
arrange(score)
# Sort by score descending (highest first)
pupils %>%
arrange(desc(score))
Original: name score Ade 85 Bola 70 Chidi 90 Dami 65 arrange(desc(score)): name score Chidi 90 Ade 85 Bola 70 Dami 65
Mini summary: arrange() sorts rows by column values.
We can combine filter(), select(), mutate(), arrange(), and summarise() in a single pipeline.
Example: We want to:
pupils %>%
filter(score > 70) %>%
select(name, score) %>%
mutate(bonus = score + 5) %>%
arrange(desc(score))
Result: name score bonus Chidi 90 95 Ade 85 90
Mini summary: Pipes let you chain multiple verbs in one clear sequence.
Definition: Missing data are empty values, shown as NA in R.
Why it is important: Missing values can break calculations if not handled.
Simple explanation: It's like a page missing from your book – you need to decide what to do.
Real-life example: A survey form where someone didn't answer a question.
School example: A pupil was absent on the day of the test.
Home example: You forgot to record the time you spent reading.
Nigerian example: A farmer didn't record the harvest for one month.
How to handle: Use filter() to remove NAs, or use na.rm = TRUE inside functions like mean().
# Remove rows with NA in score pupils %>% filter(!is.na(score)) # Get mean ignoring NAs summarise(avg = mean(score, na.rm = TRUE))
Mini summary: Always check for NA values and decide to remove them or ignore them in calculations.
Definition: rename() changes the names of columns.
Why it is important: Column names might be too long, misspelled, or unclear.
Simple explanation: It's like giving your pet a new nickname.
Real-life example: You change a file name to make it more descriptive.
School example: Your teacher renames "Test_1" to "Math_Test".
Home example: You rename your folders from "Stuff" to "Schoolwork".
Nigerian example: An analyst renames a column from "Pop" to "Population".
pupils %>%
rename(Score = score, Name = name)
Mini summary: rename() changes column names to be clearer.
Definition: distinct() removes duplicate rows from your data.
Why it is important: Duplicates can overcount and give wrong results.
Simple explanation: It's like removing double entries in your list.
Real-life example: You delete duplicate contacts on your phone.
School example: You remove duplicate names from the class register.
Home example: You make sure you don't have two of the same toy listed.
Nigerian example: A voter register removes duplicate names.
pupils %>% distinct() # removes exact duplicate rows pupils %>% distinct(name, .keep_all = TRUE) # keep only unique names
Mini summary: distinct() removes duplicate rows.
Let's use a small dataset about Nigerian states and their populations (example). We will wrangle it.
# Sample data (population in millions)
states <- data.frame(
State = c("Lagos", "Kano", "Oyo", "Lagos", "Rivers", "Kano"),
Population = c(20, 15, 8, 20, 7, 15),
Region = c("SW", "NW", "SW", "SW", "SS", "NW")
)
# We have duplicates! Let's remove them.
states_unique <- states %>% distinct(State, .keep_all = TRUE)
# Filter to only SW states
sw_states <- states_unique %>% filter(Region == "SW")
# Select State and Population
sw_pop <- sw_states %>% select(State, Population)
# Arrange by population descending
sw_pop %>% arrange(desc(Population))
Result: State Population Lagos 20 Oyo 8
Mini summary: You can use all dplyr verbs on Nigerian data to clean and explore it.
We have learned six main verbs:
filter() – pick rows.select() – pick columns.mutate() – create new columns.summarise() – get summaries (mean, sum, etc.).arrange() – sort rows.group_by() – split data into groups.And the pipe %>% connects them.
Remember: These verbs make data wrangling fun and easy!
%>% operator makes code readable.dplyr functions do not change the original data unless you assign the result.library(dplyr)data %>% distinct()data %>% filter(condition)data %>% select(col1, col2)data %>% mutate(new = old * 2)data %>% summarise(mean = mean(col))data %>% arrange(desc(col))filter() to find products with low stock.arrange() to sort students by grades.summarise() to get average patient age.filter() to get data for only Lagos State.group_by() and summarise() to calculate average income by region.mutate() to add a "pass/fail" column based on scores.dplyr package was created by Hadley Wickham, a famous data scientist.dplyr is used by companies like Facebook and Google.dplyr is one of the most popular.dplyr can work with large datasets very quickly because it uses C++ behind the scenes.dplyr with databases without loading all data into memory.dtplyr that uses dplyr syntax on data.table for even more speed.dplyr with library(dplyr).%>% to chain commands.filter() picks rows, select() picks columns.mutate() creates new columns, summarise() gives summaries.arrange() sorts, group_by() splits into groups.dplyr before using its functions.filter() with the wrong condition (e.g., == instead of =).na.rm = TRUE when calculating means with missing values.dplyr does not modify in place.NA values early.glimpse() or str() to understand your data before wrangling.
data
|
V
filter() --> (keeps rows)
|
V
select() --> (keeps columns)
|
V
mutate() --> (adds columns)
|
V
arrange() --> (sorts rows)
Before filter: +------+-----+-------+ | name | age | score | +------+-----+-------+ | Ade | 10 | 85 | | Bola | 11 | 70 | | Chidi| 9 | 90 | +------+-----+-------+ filter(score > 80): +------+-----+-------+ | name | age | score | +------+-----+-------+ | Ade | 10 | 85 | | Chidi| 9 | 90 | +------+-----+-------+
Before select: +------+-----+-------+ | name | age | score | +------+-----+-------+ | Ade | 10 | 85 | +------+-----+-------+ select(name, score): +------+-------+ | name | score | +------+-------+ | Ade | 85 | +------+-------+
| Verb | What it does | Example |
|---|---|---|
| filter() | Picks rows based on condition | filter(score > 80) |
| select() | Picks columns by name | select(name, score) |
| mutate() | Creates new columns | mutate(total = score + 5) |
| summarise() | Calculates summary stats | summarise(avg = mean(score)) |
| arrange() | Sorts rows | arrange(desc(score)) |
| group_by() | Splits data into groups | group_by(age) |
In this module, we learned how to wrangle data – that is, clean and prepare it for analysis.
We used the dplyr package, which provides simple verbs: filter(), select(), mutate(),
summarise(), arrange(), and group_by(). We also learned the pipe %>% to chain commands.
We handled missing values (NA), removed duplicates, and renamed columns.
Data wrangling is an essential step before any analysis or visualisation.
Remember: clean data leads to clear insights!
install.packages("dplyr")distinct().arrange().| Verb | Description |
|---|---|
| 1. filter | A. Adds new columns |
| 2. select | B. Picks rows that meet condition |
| 3. mutate | C. Chooses columns |
| 4. summarise | D. Sorts rows |
| 5. arrange | E. Calculates summary statistics |
Answers: 1-B, 2-C, 3-A, 4-E, 5-D
In groups of four, create a small dataset (10 rows) about your favourite foods, with columns: food, cost, rating. Then use dplyr to:
Present your code and output to the class.
Use the iris dataset (built-in) and dplyr to:
Title: "Clean the School Data"
You are given a messy dataset of school attendance (columns: name, class, days_present, days_absent) with duplicates, missing values, and errors. Use dplyr to:
Using the mtcars dataset, perform the following using dplyr:
Find a real, messy dataset online (e.g., from Kaggle or Nigerian open data). Use dplyr to perform a complete cleaning and summarisation. Write a short report (2 paragraphs) describing your steps and what you discovered.
Fill-in-the-Blank: 1. wrangling, 2. dplyr, 3. %>%, 4. filter, 5. select, 6. mutate, 7. summarise, 8. arrange, 9. group_by, 10. NA.
True/False: 1F, 2T, 3F, 4F, 5F, 6T, 7T, 8F, 9T, 10T.
Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6A, 7A, 8B, 9A, 10C, 11A, 12C, 13B, 14A, 15C.
filter(), select(), mutate(), summarise(), arrange(), group_by().%>% chains commands.In Module 9, we will learn about joining datasets – combining information from different tables, like merging pupil data with class data.
We will use dplyr joins: left_join(), inner_join(), and more.
Before that, practise the verbs you learned in this module on different datasets.
Well done! You are becoming a data wrangler!