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.
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 |
|---|---|---|---|
| Ada | 13 | 85 | JSS 2 |
| Tunde | 14 | 72 | JSS 2 |
| Chika | 13 | Missing | JSS 2 |
| Ada | 13 | 85 | JSS 2 |
| Emeka | 150 | 65 | JSS 3 |
This dataset has some problems:
Data cleaning helps us identify and deal with these problems before using the information to make decisions.
Data transformation means changing the structure, format, or values of information to make it easier to analyse.
For example, you may want to:
Cleaning fixes problems, while transformation changes or reorganises data for a particular purpose.
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.
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.
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.
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.
colSums(is.na(students))
This command counts the missing values in each column.
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.
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.
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.
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.
duplicated(students)
R returns TRUE for rows that duplicate an earlier row and
FALSE for rows that are not 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.
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.
age <- c("13", "14", "15")
age <- as.numeric(age)
print(age)
scores <- c(85, 72, 90)
scores_text <- as.character(scores)
print(scores_text)
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)
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.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)
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)
The select() function allows you to choose specific columns.
student_scores <- select(students, Name, Score)
print(student_scores)
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))
The mutate() function creates a new column or changes an existing one.
students <- mutate(
students,
Result = ifelse(Score >= 50, "Pass", "Fail")
)
print(students)
The rename() function changes a column name.
students <- rename(students, Student_Name = Name)
print(students)
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.
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.
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:
In this module, you have learned how to:
is.na().ifelse().filter(), select(), arrange(), mutate(), and rename().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.