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

Module Seven

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

Module 7: Basic Statistical Analysis in R

1. Introduction

In the previous module, you learned how to clean and transform data using R. Now, it is time to learn how to study that data and discover useful information.

Imagine a school in Ibadan has examination results for 100 students. The school wants to know the average score, the highest score, the lowest score, and how many students passed.

Instead of checking every student's result manually, you can use R to calculate these values quickly.

This process is called statistical analysis.

2. What Is Statistical Analysis?

Statistical analysis is the process of collecting, organising, calculating, and interpreting data to understand what it means.

For example, a supermarket in Lagos can use statistical analysis to:

  • Calculate its total sales for the month.
  • Find the average amount customers spend.
  • Identify its most expensive product.
  • Find the product with the lowest sales value.
  • Compare sales across different months.

Statistical analysis helps people make decisions based on information rather than guesswork.

3. Creating Data for Statistical Analysis

Before performing calculations, let's create a dataset containing examination scores for five students.

scores <- c(85, 72, 90, 65, 78)

print(scores)

The function c() combines the scores into a vector. We can now use different R functions to analyse the information.

4. Calculating the Total

The total is the result you get when you add all the values together. In R, you can calculate the total using the sum() function.

scores <- c(85, 72, 90, 65, 78)

total_score <- sum(scores)

print(total_score)

R adds all five examination scores and stores the answer in total_score.

Real-life example: A shop owner can use sum() to calculate the total sales made during a day.

5. Finding the Average (Mean)

The average tells you the typical value in a group of numbers. In statistics, this is called the mean.

To calculate the average examination score, use:

average_score <- mean(scores)

print(average_score)

R adds all the scores and divides the total by the number of scores.

The formula for calculating the mean is:

Mean = Sum of all values รท Number of values

For example, if five students score a total of 390 marks, their average score is 390 divided by 5, which equals 78.

6. Finding the Highest and Lowest Values

Sometimes, you want to identify the largest or smallest value in a dataset.

A. Maximum Value

The max() function finds the highest value.

highest_score <- max(scores)

print(highest_score)

B. Minimum Value

The min() function finds the lowest value.

lowest_score <- min(scores)

print(lowest_score)

These functions are useful when comparing examination results, business sales, customer payments, or product prices.

7. Understanding the Median

The median is the middle value in a dataset after the numbers have been arranged from the smallest to the largest.

For example, consider these examination scores:

scores <- c(65, 72, 78, 85, 90)

median_score <- median(scores)

print(median_score)

The middle value is 78, so the median score is 78.

If a dataset has an even number of values, R calculates the median by finding the average of the two middle values.

numbers <- c(10, 20, 30, 40)

median(numbers)

The two middle values are 20 and 30. Their average is 25.

8. Understanding Mode

The mode is the value that appears most frequently in a dataset.

For example:

scores <- c(70, 80, 80, 90, 80, 75, 70)

In this example, 80 appears three times. Therefore, 80 is the mode.

Unlike mean and median, base R does not provide a simple statistical mode() function for finding the most frequently occurring value. The following code can help you find it:

scores <- c(70, 80, 80, 90, 80, 75, 70)

frequency <- table(scores)

mode_score <- names(frequency)[which.max(frequency)]

print(mode_score)

The table() function counts how often each value appears, while which.max() identifies the highest frequency.

9. Understanding Range

Range shows the difference between the highest and lowest values in a dataset.

The formula is:

Range = Highest Value - Lowest Value

highest_score <- max(scores)

lowest_score <- min(scores)

score_range <- highest_score - lowest_score

print(score_range)

Range helps you understand how far apart the largest and smallest values are.

10. Understanding Variance and Standard Deviation

Two important statistical measurements are variance and standard deviation. They help you understand how spread out values are.

A. Variance

Variance measures how far values are spread around the mean. A larger variance generally means the values are more spread out.

variance_score <- var(scores)

print(variance_score)

R's var() function calculates sample variance by default.

B. Standard Deviation

Standard deviation measures how much values typically vary from the mean. It is expressed in the same units as the original data.

standard_deviation <- sd(scores)

print(standard_deviation)

A small standard deviation means the values are relatively close to the mean. A large standard deviation means they are more spread out.

11. Counting Values in a Dataset

Sometimes, you need to know how many records are contained in a dataset. R provides the length() function for counting the number of elements in a vector.

scores <- c(85, 72, 90, 65, 78)

number_of_students <- length(scores)

print(number_of_students)

The table() function can also count how frequently different categories or values appear.

grades <- c("A", "B", "A", "C", "B", "A")

table(grades)

This tells you how many times each grade appears.

12. Working with Missing Values

Sometimes, datasets contain missing information. R represents missing values using NA.

Consider this example:

scores <- c(85, 72, NA, 90, 65)

mean(scores)

The result will be NA because one of the scores is missing. You can tell R to ignore missing values when calculating the average.

mean(scores, na.rm = TRUE)

The argument na.rm = TRUE means that missing values should be removed from the calculation.

You can also use it with functions such as sum(), max(), and min().

sum(scores, na.rm = TRUE)

max(scores, na.rm = TRUE)

min(scores, na.rm = TRUE)

13. Performing Statistical Analysis on a Data Frame

In real projects, information is usually stored in data frames rather than individual vectors.

Let's create a student results dataset:

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

print(students)

Now calculate the average examination score:

mean(students$Score)

Find the highest score:

max(students$Score)

Find the lowest score:

min(students$Score)

Calculate the median score:

median(students$Score)

Display a statistical summary of the entire dataset:

summary(students)

The dollar sign $ allows you to access a particular column inside a data frame.

14. Analysing Supermarket Sales in R

Imagine a supermarket in Lagos wants to understand its daily sales. It records the following information:

sales <- data.frame(
  Product = c("Rice", "Beans", "Garri", "Oil", "Sugar"),
  Quantity = c(5, 3, 4, 2, 6),
  Amount = c(40000, 13500, 12000, 12000, 9000)
)

print(sales)

Calculate the total sales:

sum(sales$Amount)

Calculate the average sales value:

mean(sales$Amount)

Find the highest sales value:

max(sales$Amount)

Find the lowest sales value:

min(sales$Amount)

Calculate the total quantity of products sold:

sum(sales$Quantity)

These calculations help the supermarket understand its performance and make better business decisions.

15. Common Statistical Functions in R

Function Purpose
sum()Calculates the total.
mean()Calculates the average.
median()Finds the middle value.
max()Finds the highest value.
min()Finds the lowest value.
range()Returns the minimum and maximum values.
var()Calculates sample variance.
sd()Calculates sample standard deviation.
length()Counts the elements in a vector.
table()Counts how frequently values occur.
summary()Provides a statistical summary.

16. Practical Exercise

A school in Ibadan wants you to analyse the examination results of its students. Use R to complete the following activities.

Create this dataset:

scores <- c(65, 80, 75, 90, 55, 85, 70, 95, 60, 80)

Complete these tasks:

  1. Calculate the total of all examination scores.
  2. Calculate the average score.
  3. Find the highest score.
  4. Find the lowest score.
  5. Calculate the median score.
  6. Calculate the range.
  7. Calculate the variance.
  8. Calculate the standard deviation.
  9. Count the number of students.
  10. Display a statistical summary of the scores.

17. Module Summary

In this module, you have learned how to:

  • Understand statistical analysis and its importance.
  • Calculate totals using sum().
  • Calculate averages using mean().
  • Find the median and mode.
  • Identify the highest and lowest values.
  • Calculate range, variance, and standard deviation.
  • Count records and categories.
  • Handle missing values during calculations.
  • Perform basic statistical analysis on data frames.

18. What Is Next?

You have now learned how to use R to calculate and understand important information in a dataset.

But numbers alone do not always make information easy to understand. Sometimes, you need charts and graphs to explain what the data is telling you.

In the final module, Data Visualisation and Practical Project with R, you will learn how to create charts, visualise information, and complete a simple data analysis project using R.

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