Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← R for Data Analysis Expert · Lesson 9 of 17

Module Eight

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
9
Module 8 · R for Data Analysis · Data Wrangling with dplyr

Module 8 · Data Wrangling – Cleaning and Preparing Data

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!


Learning Objectives

  • Understand what data wrangling means.
  • Install and load the dplyr package.
  • Use filter() to choose rows that meet a condition.
  • Use select() to choose specific columns.
  • Use mutate() to create new columns.
  • Use summarise() to get summary statistics (like mean, sum).
  • Use arrange() to sort data.
  • Use the pipe operator %>% to chain commands.
  • Apply these tools to real data, including Nigerian examples.
  • Recognise dirty data and know how to fix common issues.

Warm-up Story: The Messy Market List

Chidi loves helping his mother at the market. One day, his mother gave him a messy list of items to buy:

  • tomato, 5
  • onion, 3
  • yam, 2
  • tomato, 4 (wait, she added tomatoes again!)
  • pepper, 1
  • onion, 2 (another onion?)

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:

  1. He combined the tomatoes: 5 + 4 = 9.
  2. He combined the onions: 3 + 2 = 5.
  3. He sorted the items alphabetically.

Now the list was clear:

  • onion – 5
  • pepper – 1
  • tomato – 9
  • yam – 2

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.


Main Lessons

Lesson 1: What is Data Wrangling?

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.


Lesson 2: Meet dplyr – Your Data Wrangling Toolkit

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.


Lesson 3: The Pipe Operator %>% – Connecting Steps

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.


Lesson 4: filter() – Picking Rows

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.


Lesson 5: select() – Picking Columns

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.


Lesson 6: mutate() – Creating New Columns

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.


Lesson 7: summarise() – Getting Summaries

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.


Lesson 8: group_by() + summarise() – Grouped Summaries

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.


Lesson 9: arrange() – Sorting Data

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.


Lesson 10: Combining Verbs – The Power of Pipes

We can combine filter(), select(), mutate(), arrange(), and summarise() in a single pipeline.

Example: We want to:

  1. Filter to only pupils with score > 70.
  2. Select name and score.
  3. Add a column "bonus" = score + 5.
  4. Sort by score descending.
   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.


Lesson 11: Handling Missing Data – NA Values

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.


Lesson 12: Renaming Columns – rename()

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.


Lesson 13: Distinct Rows – distinct()

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.


Lesson 14: Applying dplyr to Real Nigerian Data

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.


Lesson 15: Summary of dplyr Verbs

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!


Key Vocabulary

Data Wrangling
Cleaning and organising data to make it ready for analysis.
dplyr
An R package with verbs for data manipulation.
Pipe (%>%)
An operator that chains commands together.
filter()
Selects rows that meet a condition.
select()
Selects columns by name.
mutate()
Adds new columns.
summarise()
Calculates summary statistics.
arrange()
Sorts rows.
group_by()
Splits data into groups for grouped operations.
NA
Missing value in R.

Important Concepts

  • Tidy Data: Each variable is a column, each observation is a row.
  • Piping: The %>% operator makes code readable.
  • Non-destructive: dplyr functions do not change the original data unless you assign the result.
  • Vectorized Operations: Operations are applied to whole columns efficiently.

Step-by-Step Explanations

How to clean a dataset with dplyr:

  1. Load dplyr: library(dplyr)
  2. Remove duplicates: data %>% distinct()
  3. Filter rows: data %>% filter(condition)
  4. Select columns: data %>% select(col1, col2)
  5. Mutate (add columns): data %>% mutate(new = old * 2)
  6. Summarise: data %>% summarise(mean = mean(col))
  7. Arrange: data %>% arrange(desc(col))

Real-life Examples

  • A shop uses filter() to find products with low stock.
  • A teacher uses arrange() to sort students by grades.
  • A hospital uses summarise() to get average patient age.

Nigerian Examples

  • A government agency uses filter() to get data for only Lagos State.
  • An economist uses group_by() and summarise() to calculate average income by region.
  • A school uses mutate() to add a "pass/fail" column based on scores.

Fun Examples Children Relate To

  • filter(): Select only your favourite toys from a list.
  • select(): Choose only the name and colour of your toys.
  • mutate(): Add a column for "toy value" = price + age.
  • arrange(): Sort your toys by size from smallest to largest.

Everyday Examples

  • You use a shopping list and cross out items you already bought (filter).
  • You write a list of your friends' phone numbers and sort them alphabetically.
  • You calculate your total pocket money for the month.

Teacher Notes

  • Emphasise that real data is messy and wrangling is a necessary step.
  • Use small datasets for practice so pupils can see the changes.
  • Encourage pupils to experiment with different verbs.
  • Relate the verbs to everyday actions (filter = sieve, select = choose, etc.).

Parent Tips

  • Help your child collect simple data at home (e.g., daily temperatures).
  • Ask them to clean the data (remove duplicates, sort).
  • Discuss how cleaning data helps in real life (e.g., organising a party).

Interesting Facts

  • The dplyr package was created by Hadley Wickham, a famous data scientist.
  • Data scientists spend about 80% of their time on data wrangling!
  • dplyr is used by companies like Facebook and Google.
  • R has over 15,000 packages, and dplyr is one of the most popular.

Did You Know?

  • dplyr can work with large datasets very quickly because it uses C++ behind the scenes.
  • You can use dplyr with databases without loading all data into memory.
  • There is a package called dtplyr that uses dplyr syntax on data.table for even more speed.

Remember This

  • Always load dplyr with library(dplyr).
  • Use the pipe %>% to chain commands.
  • filter() picks rows, select() picks columns.
  • mutate() creates new columns, summarise() gives summaries.
  • arrange() sorts, group_by() splits into groups.

Common Mistakes

  • Forgetting to load dplyr before using its functions.
  • Using filter() with the wrong condition (e.g., == instead of =).
  • Not using na.rm = TRUE when calculating means with missing values.
  • Forgetting to assign the result to a new variable; dplyr does not modify in place.
  • Using the pipe without proper indentation (though it still works, it's harder to read).

Best Practices

  • Start with a clear question: "What do I want to do with this data?"
  • Use descriptive variable names.
  • Chain operations with pipes for readability.
  • Check for NA values early.
  • Use glimpse() or str() to understand your data before wrangling.

ASCII Illustrations

Piping concept

   data
     |
     V
   filter()   -->  (keeps rows)
     |
     V
   select()   -->  (keeps columns)
     |
     V
   mutate()   -->  (adds columns)
     |
     V
   arrange()  -->  (sorts rows)

Filtering 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    |
   +------+-----+-------+

Selecting columns

   Before select:
   +------+-----+-------+
   | name | age | score |
   +------+-----+-------+
   | Ade  | 10  | 85    |
   +------+-----+-------+

   select(name, score):
   +------+-------+
   | name | score |
   +------+-------+
   | Ade  | 85    |
   +------+-------+

Comparison Tables

dplyr Verbs and Their Uses
VerbWhat it doesExample
filter()Picks rows based on conditionfilter(score > 80)
select()Picks columns by nameselect(name, score)
mutate()Creates new columnsmutate(total = score + 5)
summarise()Calculates summary statssummarise(avg = mean(score))
arrange()Sorts rowsarrange(desc(score))
group_by()Splits data into groupsgroup_by(age)

End-of-Module Summary

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!


Frequently Asked Questions

1. What is data wrangling?
Cleaning and organising data to make it useful.
2. What is dplyr?
An R package for data manipulation.
3. How do I install dplyr?
install.packages("dplyr")
4. What does filter() do?
Selects rows that meet a condition.
5. What is the pipe %>%?
It chains commands together.
6. How do I remove duplicates?
Use distinct().
7. What is mutate() used for?
To create new columns.
8. How do I sort data?
Use arrange().
9. What is NA?
A missing value in R.
10. Can I use dplyr with other packages?
Yes, it works well with ggplot2, tidyr, and others.

Review Questions

  1. What is data wrangling?
  2. What package do we use for data wrangling in R?
  3. What does the pipe %>% do?
  4. Which verb selects rows based on a condition?
  5. Which verb selects columns?
  6. Which verb creates new columns?
  7. Which verb calculates summary statistics?
  8. Which verb sorts data?
  9. How do you remove duplicate rows?
  10. What does NA represent?
  11. How do you handle missing values in summarise()?
  12. What does group_by() do?
  13. Give an example of using filter() in real life.
  14. What is the benefit of using pipes?
  15. Why is data wrangling important before making graphs?

Fill-in-the-Blank Exercises

  1. Data ______ means cleaning and organising data. (wrangling)
  2. ______ is an R package for data manipulation. (dplyr)
  3. The pipe operator is ______. (%>%)
  4. ______ selects rows that meet a condition. (filter)
  5. ______ selects columns by name. (select)
  6. ______ creates new columns. (mutate)
  7. ______ calculates summary statistics. (summarise)
  8. ______ sorts rows. (arrange)
  9. ______ splits data into groups. (group_by)
  10. Missing values in R are shown as ______. (NA)

True or False Exercises

  1. Data wrangling is only for experts. (False)
  2. dplyr is a package in R. (True)
  3. The pipe operator is written as <-. (False)
  4. filter() picks columns. (False)
  5. select() picks rows. (False)
  6. mutate() adds new columns. (True)
  7. summarise() gives one row of summaries. (True)
  8. arrange() sorts columns. (False)
  9. group_by() is used with summarise(). (True)
  10. NA means missing value. (True)

Multiple Choice Questions

  1. Which package is used for data wrangling?
    A. ggplot2 B. dplyr C. tidyr D. readr
    Answer: B
  2. Which verb selects rows?
    A. select() B. filter() C. mutate() D. arrange()
    Answer: B
  3. Which verb creates new columns?
    A. summarise() B. mutate() C. filter() D. arrange()
    Answer: B
  4. What does the pipe %>% do?
    A. Sorts data B. Chains commands C. Filters rows D. Selects columns
    Answer: B
  5. Which verb gives summary statistics?
    A. mutate() B. summarise() C. filter() D. select()
    Answer: B
  6. How do you sort data in descending order?
    A. arrange(desc(col)) B. arrange(col) C. sort(desc(col)) D. order(col)
    Answer: A
  7. What does NA stand for?
    A. Not Available B. No Answer C. New Attribute D. None
    Answer: A
  8. Which verb removes duplicate rows?
    A. unique() B. distinct() C. filter() D. arrange()
    Answer: B
  9. Which verb splits data into groups?
    A. group_by() B. split() C. arrange() D. filter()
    Answer: A
  10. What is the first step to use dplyr?
    A. install.packages("dplyr") B. library(dplyr) C. Both A and B D. None
    Answer: C
  11. Which verb renames columns?
    A. rename() B. select() C. mutate() D. summarise()
    Answer: A
  12. Which function shows structure of data?
    A. str() B. glimpse() C. Both A and B D. view()
    Answer: C
  13. What is the result of summarise()?
    A. A new column B. A summary table C. Filtered rows D. Sorted data
    Answer: B
  14. Can dplyr be used with databases?
    A. Yes B. No C. Only with small data D. Only with CSV
    Answer: A
  15. Which of these is NOT a dplyr verb?
    A. filter B. select C. plot D. mutate
    Answer: C

Matching Exercises

VerbDescription
1. filterA. Adds new columns
2. selectB. Picks rows that meet condition
3. mutateC. Chooses columns
4. summariseD. Sorts rows
5. arrangeE. Calculates summary statistics

Answers: 1-B, 2-C, 3-A, 4-E, 5-D


Short Answer Questions

  1. What is data wrangling and why is it important?
  2. Explain the difference between filter() and select().
  3. How do you use the pipe operator? Give an example.
  4. What does mutate() do? Provide a simple example.
  5. How do you handle missing values in dplyr?

Scenario-based Exercises

  1. Scenario: You have a dataset of pupils with columns: name, age, class, score. You want to get the average score for each class. Which verbs would you use?
  2. Scenario: Your data has duplicate rows and missing scores. How would you clean it?
  3. Scenario: You want to create a new column "grade" based on score (A for >80, B for 60-80, etc.). Which verb do you use?

Group Activity

In groups of four, create a small dataset (10 rows) about your favourite foods, with columns: food, cost, rating. Then use dplyr to:

  • Filter to only foods with rating > 4.
  • Select food and cost.
  • Add a new column "total_cost" = cost * 2.
  • Arrange by cost descending.

Present your code and output to the class.


Individual Activity

Use the iris dataset (built-in) and dplyr to:

  1. Filter to only setosa species.
  2. Select Sepal.Length and Petal.Length.
  3. Add a new column "ratio" = Sepal.Length / Petal.Length.
  4. Arrange by ratio descending.

Classroom Discussion Questions

  1. Why is data wrangling an important skill?
  2. What happens if you don't clean your data before analysis?
  3. How can data wrangling help Nigerian businesses?
  4. Which dplyr verb do you find most useful and why?

Mini Project

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:

  1. Remove duplicates.
  2. Filter out rows with missing values.
  3. Add a column "total_days" = days_present + days_absent.
  4. Calculate average attendance per class.
  5. Sort by class.

Practical Assignment

Using the mtcars dataset, perform the following using dplyr:

  1. Filter to cars with more than 4 cylinders.
  2. Select mpg, cyl, and hp.
  3. Add a new column "hp_per_cyl" = hp / cyl.
  4. Group by cyl and calculate average mpg.
  5. Arrange by average mpg descending.

Challenge Exercise

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.


Quiz Answers

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.


Key Takeaways

  • Data wrangling is cleaning and organising data.
  • dplyr provides verbs: filter(), select(), mutate(), summarise(), arrange(), group_by().
  • The pipe %>% chains commands.
  • Always check for NA values.
  • Use distinct() to remove duplicates.
  • Wrangling makes data ready for visualisation and analysis.

Preparation for the Next Module

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!


🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→