Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to R for Data Analysis ยท Lesson 7 of 9

Module Six

๐Ÿ“– 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.
7

Module 6: Data Cleaning and Transformation in R

1. Introduction

In the previous module, you learned how to import and explore datasets in R. But what happens when the information you import contains mistakes, missing values, duplicate records, or inconsistent entries?

You cannot always analyse data immediately after importing it. Sometimes, you must clean and organise it first.

This process is called data cleaning and transformation. It helps you make information accurate, consistent, and ready for analysis.

2. What Is Data Cleaning?

Data cleaning means finding and correcting problems in a dataset. These problems may include missing information, repeated records, spelling mistakes, or incorrect values.

Imagine a school in Ibadan has a student records file like this:

Name Age Score Class
Ada1385JSS 2
Tunde1472JSS 2
Chika13MissingJSS 2
Ada1385JSS 2
Emeka15065JSS 3

This dataset has some problems:

  • Chika's examination score is missing.
  • Ada's record appears twice.
  • Emeka's age is 150, which may be an incorrect entry.

Data cleaning helps us identify and deal with these problems before using the information to make decisions.

3. What Is Data Transformation?

Data transformation means changing the structure, format, or values of information to make it easier to analyse.

For example, you may want to:

  • Convert names to uppercase or lowercase.
  • Create a new column showing whether a student passed or failed.
  • Calculate the total sales for each product.
  • Convert text values into numbers.
  • Arrange information into a more useful format.

Cleaning fixes problems, while transformation changes or reorganises data for a particular purpose.

4. Creating a Dataset for Practice

Before learning how to clean data, let's create a small dataset containing student information.

students <- data.frame(
  Name = c("Ada", "Tunde", "Chika", "Ada", "Emeka"),
  Age = c(13, 14, 13, 13, 150),
  Score = c(85, 72, NA, 85, 65),
  Class = c("JSS 2", "JSS 2", "JSS 2", "JSS 2", "JSS 3")
)

print(students)

Notice the value NA in Chika's score. In R, NA represents missing information.

5. Identifying Missing Values

Missing values occur when information is not available in a dataset. For example, a student may not have an examination score because the result was not entered.

R provides useful functions for finding missing values.

A. is.na()

The is.na() function checks whether a value is missing.

is.na(students$Score)

R returns TRUE for missing values and FALSE for values that are present.

B. sum(is.na())

You can count the number of missing values in a column using:

sum(is.na(students$Score))

This tells you how many examination scores are missing.

C. Finding Missing Values in the Entire Dataset

colSums(is.na(students))

This command counts the missing values in each column.

6. Handling Missing Values

After identifying missing values, you must decide how to handle them. The correct method depends on the type of information and the purpose of the analysis.

A. Removing Rows with Missing Values

You can remove rows that contain missing values using na.omit().

clean_students <- na.omit(students)

print(clean_students)

This creates a new dataset without rows containing missing values. Be careful: removing rows may cause you to lose useful information.

B. Replacing Missing Values

Sometimes, you may replace missing numerical values with a suitable value. One possible method is to use the average of the available scores.

average_score <- mean(students$Score, na.rm = TRUE)

students$Score[is.na(students$Score)] <- average_score

print(students)

The argument na.rm = TRUE tells R to ignore missing values when calculating the average.

Important: Replacing a missing score with an average is only suitable when the method makes sense for the analysis. Never invent values or hide missing information without a valid reason.

7. Identifying and Removing Duplicate Records

Duplicate records are repeated entries in a dataset. They can cause incorrect calculations, especially when counting students, customers, or sales transactions.

R provides the duplicated() function to identify repeated records.

Checking for Duplicates

duplicated(students)

R returns TRUE for rows that duplicate an earlier row and FALSE for rows that are not duplicates.

Removing Duplicates

students_unique <- students[!duplicated(students), ]

print(students_unique)

The exclamation mark ! means NOT. It keeps records that are not duplicates.

If you want to check duplicates based on a particular column, such as student names, you can use:

duplicated(students$Name)

Be careful when removing duplicates based on names alone. Two different students may have the same name. Use a reliable unique identifier, such as a student ID, when available.

8. Correcting Data Types

Sometimes, information is stored in the wrong format. For example, a student's age may be stored as text instead of a number.

R provides functions for converting data types.

A. Converting Text to Numbers

age <- c("13", "14", "15")

age <- as.numeric(age)

print(age)

B. Converting Numbers to Text

scores <- c(85, 72, 90)

scores_text <- as.character(scores)

print(scores_text)

C. Converting Text to Factors

Factors are useful when working with categories such as class, gender, or product type.

class_name <- c("JSS 1", "JSS 2", "JSS 3")

class_name <- as.factor(class_name)

print(class_name)

You can check the data type of a variable using:

class(class_name)

9. Changing and Creating Columns

Data transformation also involves changing existing columns or creating new ones.

For example, imagine you want to classify students as Pass or Fail.

students <- data.frame(
  Name = c("Ada", "Tunde", "Chika", "Emeka"),
  Score = c(85, 42, 65, 35)
)

students$Result <- ifelse(
  students$Score >= 50,
  "Pass",
  "Fail"
)

print(students)

Let's understand what happened:

  • students$Result creates a new column called Result.
  • ifelse() checks a condition.
  • Students scoring 50 or above receive Pass.
  • Students scoring below 50 receive Fail.

10. Transforming Data with dplyr

R has many packages that make data cleaning and transformation easier. One popular package is called dplyr.

The package provides simple functions for selecting columns, filtering rows, creating new columns, and arranging records.

First, install and load the package:

install.packages("dplyr")

library(dplyr)

A. filter()

The filter() function selects rows that meet a condition. For example, to display students who scored at least 50:

passed_students <- filter(students, Score >= 50)

print(passed_students)

B. select()

The select() function allows you to choose specific columns.

student_scores <- select(students, Name, Score)

print(student_scores)

C. arrange()

The arrange() function sorts records. To arrange students from the lowest score to the highest:

arrange(students, Score)

To arrange students from the highest score to the lowest:

arrange(students, desc(Score))

D. mutate()

The mutate() function creates a new column or changes an existing one.

students <- mutate(
  students,
  Result = ifelse(Score >= 50, "Pass", "Fail")
)

print(students)

E. rename()

The rename() function changes a column name.

students <- rename(students, Student_Name = Name)

print(students)

11. Using the Pipe Operator

The pipe operator |> allows you to connect several operations. It passes the result of one step into the next step.

For example, you can filter students who passed and then arrange them by score:

passed_students <- students |>
  filter(Score >= 50) |>
  arrange(desc(Score))

print(passed_students)

This makes your code easier to read when performing several operations. The pipe operator is available in modern versions of R.

12. Practical Example: Cleaning a Supermarket Dataset

Imagine a supermarket in Lagos has collected sales information. Some product names contain inconsistent capitalisation, and some records are repeated.

sales <- data.frame(
  Product = c("rice", "BEANS", "Garri", "rice"),
  Quantity = c(5, 3, 4, 5),
  Price = c(8000, 4500, 3000, 8000)
)

print(sales)

Step 1: Convert product names to a consistent format.

sales$Product <- tools::toTitleCase(
  tolower(sales$Product)
)

Step 2: Remove duplicate records.

sales_unique <- sales[!duplicated(sales), ]

Step 3: Create a Total column.

sales_unique$Total <-
  sales_unique$Quantity * sales_unique$Price

Step 4: Display the cleaned dataset.

print(sales_unique)

You now have a more organised dataset with consistent product names, duplicate records removed, and a new column showing the total value of each record.

13. Best Practices for Data Cleaning

  • Always inspect your dataset before making changes.
  • Keep an original copy of important data.
  • Do not remove records without understanding why they are repeated.
  • Investigate unusual values before correcting them.
  • Choose an appropriate method for handling missing values.
  • Use clear column names that describe the information.
  • Check your results after every major transformation.
  • Document important changes so other people can understand your work.

14. Practical Exercise

A school in Ibadan gives you a dataset containing student names, ages, and examination scores. Your task is to clean and transform the information using R.

Create this dataset:

students <- data.frame(
  Name = c("Ada", "Tunde", "Chika", "Ada", "Emeka"),
  Age = c(13, 14, 13, 13, 15),
  Score = c(85, 72, NA, 85, 45)
)

Complete these activities:

  1. Display the dataset.
  2. Identify the missing examination score.
  3. Count the number of missing values.
  4. Remove duplicate records.
  5. Create a new column called Result.
  6. Classify students who scored 50 and above as Pass.
  7. Display only the students who passed.
  8. Arrange the students by examination score from highest to lowest.

15. Module Summary

In this module, you have learned how to:

  • Understand data cleaning and transformation.
  • Identify missing values using is.na().
  • Count and handle missing information.
  • Identify and remove duplicate records.
  • Convert data from one type to another.
  • Create new columns using ifelse().
  • Use dplyr functions such as filter(), select(), arrange(), mutate(), and rename().
  • Use the pipe operator to connect data operations.

16. What Is Next?

You now know how to prepare datasets for analysis. But how can you use the information to answer questions such as: What is the average examination score? What is the highest sales value? How many customers visited a shop?

In the next module, Basic Statistical Analysis in R, you will learn how to calculate averages, totals, minimums, maximums, and other useful statistics to understand what your data is telling you.

๐Ÿ† 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.
โ†’