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

Module Four

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

Module 4: Understanding Data Structures in R

Module Introduction

Imagine you are given the examination results of 100 students in a school. How would you organise their names, ages, classes, and scores so that you can analyse the information easily?

You need a way to arrange and store the information. In R programming, these arrangements are called data structures.

Data structures help R organise information so that you can calculate, compare, sort, and analyse it. In this module, you will learn about vectors, lists, matrices, arrays, data frames, and factors.

Learning Objectives

By the end of this module, you should be able to:

  • Understand what data structures are.
  • Create and use vectors in R.
  • Understand how lists store different types of information.
  • Create matrices and arrays.
  • Work with data frames.
  • Understand factors and categorical information.
  • Choose suitable data structures for simple data analysis tasks.

1. What Are Data Structures in R?

A data structure is a way of organising and storing information inside a computer program.

Think about a school. Students' names may be stored in one list, their examination scores in another, and their class information in a separate record.

R provides different data structures for storing and managing this information.

Some important data structures in R include:

  • Vectors
  • Lists
  • Matrices
  • Arrays
  • Data Frames
  • Factors

2. Understanding Vectors in R

A vector is one of the most basic data structures in R. It stores multiple values of the same basic data type in a single object.

For example, imagine a teacher wants to store the examination scores of five students.

Instead of creating five separate variables, the teacher can store all the scores in one vector.

Creating a Vector

In R, the c() function is used to combine values into a vector.

scores <- c(75, 85, 60, 90, 70)

print(scores)

Expected output:

[1] 75 85 60 90 70

The vector contains five examination scores.

Creating a Vector of Names

You can also create a vector containing text values.

students <- c("Ade", "Chika", "Tunde", "Fatima", "Emeka")

print(students)

Accessing Values in a Vector

You can select a particular value from a vector using its position, also called its index.

scores <- c(75, 85, 60, 90, 70)

scores[1]

Result: 75

Remember that R starts counting positions from 1, not 0.

You can also select multiple values:

scores[c(1, 3, 5)]

Result: 75, 60, 70

Performing Calculations with Vectors

R can perform calculations on all the numbers inside a vector.

scores <- c(75, 85, 60, 90, 70)

sum(scores)
mean(scores)
max(scores)
min(scores)

These commands calculate the total, average, highest, and lowest scores.

3. Understanding Lists in R

A list is a data structure that can store different types of information together.

For example, a student's record may contain:

  • Name: Ade
  • Age: 13
  • Score: 85
  • Passed: TRUE

These values have different data types. A list allows you to store them together.

Creating a List

student <- list(
  name = "Ade",
  age = 13,
  score = 85,
  passed = TRUE
)

print(student)

Accessing Information in a List

You can use the dollar sign ($) to access a named item in a list.

student$name
student$age
student$score

You can also access an item using double square brackets.

student[["name"]]

Remember: Lists are useful when you want to store related information that contains different data types.

4. Understanding Matrices in R

A matrix is a data structure that stores information in rows and columns. All elements in a matrix must have the same basic data type.

Think of a matrix as a classroom results table with students' scores arranged in rows and columns.

Creating a Matrix

Use the matrix() function to create a matrix.

scores <- matrix(
  c(70, 80, 90, 60, 85, 95),
  nrow = 2,
  ncol = 3
)

print(scores)

Expected output:

     [,1] [,2] [,3]
[1,]   70   90   85
[2,]   80   60   95

By default, R fills a matrix column by column.

Understanding Matrix Rows and Columns

You can access a particular value by specifying its row and column positions.

scores[1, 2]

Result: 90

This means the value in the first row and second column is 90.

You can also use the following commands:

nrow(scores)
ncol(scores)

These commands display the number of rows and columns in the matrix.

5. Understanding Arrays in R

An array is similar to a matrix, but it can store information across more than two dimensions.

A matrix has rows and columns, while an array can have additional dimensions.

Imagine a supermarket recording sales for three products across different branches and months. An array can help organise this information across several dimensions.

Creating an Array

sales <- array(
  1:12,
  dim = c(2, 3, 2)
)

print(sales)

This creates an array with:

  • 2 rows
  • 3 columns
  • 2 layers

To access a value, specify its row, column, and layer.

sales[1, 2, 1]

Result: 3

Arrays are useful when information needs to be organised across three or more dimensions.

6. Understanding Data Frames in R

A data frame is one of the most important data structures used in data analysis.

It organises information into rows and columns, just like a table in Excel.

Each column can contain a different data type, but all columns must have the same number of rows.

For example, a school may store student names, ages, classes, and examination scores in a data frame.

Creating a Data Frame

students <- data.frame(
  name = c("Ade", "Chika", "Tunde", "Fatima"),
  age = c(13, 14, 13, 14),
  class = c("JSS 2", "JSS 3", "JSS 2", "JSS 3"),
  score = c(75, 85, 60, 90)
)

print(students)

The result will look like a table:

name age class score
Ade13JSS 275
Chika14JSS 385
Tunde13JSS 260
Fatima14JSS 390

Accessing a Column in a Data Frame

You can use the dollar sign ($) to select a particular column.

students$name
students$score

This displays the names and examination scores of the students.

Selecting a Particular Row

students[1, ]

This displays the first student's complete record.

Selecting a Particular Column

students[, "score"]

This displays the score column.

Checking the Size of a Data Frame

nrow(students)
ncol(students)
dim(students)

These commands help you find the number of rows, columns, and overall dimensions of your dataset.

7. Understanding Factors in R

A factor is used to store categorical information. Categorical information refers to data that belongs to specific groups or categories.

For example, students may belong to different classes such as JSS 1, JSS 2, and JSS 3.

Product categories may include Food, Electronics, Clothing, and Household items.

Creating a Factor

student_class <- factor(
  c("JSS 1", "JSS 2", "JSS 1", "JSS 3", "JSS 2")
)

print(student_class)

Checking the Categories

You can use the levels() function to see the categories stored in a factor.

levels(student_class)

R displays the available categories.

Counting Each Category

The table() function can help you count how many times each category appears.

table(student_class)

This is useful when analysing how many students belong to each class.

8. Comparing Data Structures in R

Data Structure Purpose Example
Vector Stores values of the same basic data type. Students' scores
List Stores different types of information together. A student's complete record
Matrix Stores same-type data in rows and columns. Examination score table
Array Stores same-type data across multiple dimensions. Sales across branches and months
Data Frame Stores information in rows and columns with different column types. Student database
Factor Stores categorical information. Student classes

9. Practical Data Analysis Project

Imagine you are helping a school in Ibadan organise its students' examination results.

You have the following information:

Name Age Class Score
Ade13JSS 275
Chika14JSS 385
Tunde13JSS 260
Fatima14JSS 390
Emeka13JSS 270

Use the following R code to create a data frame:

# Create a student dataset
students <- data.frame(
  name = c("Ade", "Chika", "Tunde", "Fatima", "Emeka"),
  age = c(13, 14, 13, 14, 13),
  class = c("JSS 2", "JSS 3", "JSS 2", "JSS 3", "JSS 2"),
  score = c(75, 85, 60, 90, 70)
)

# Display the dataset
print(students)

# Display all student scores
print(students$score)

# Calculate the average score
mean(students$score)

# Find the highest score
max(students$score)

# Find the lowest score
min(students$score)

# Count students in each class
table(students$class)

By running this code, you can organise the students' records and calculate useful information about their performance.

10. Common Mistakes to Avoid

  • Mixing data types in vectors: A vector generally stores one basic data type. If you combine numbers and text, R may convert the numbers into text.
  • Incorrect indexing: Remember that R starts counting from 1.
  • Unequal data frame columns: Every column in a basic data frame must have the same number of rows.
  • Incorrect brackets: Check that your square brackets and parentheses are properly closed.
  • Confusing lists and data frames: Lists can store different types of objects, while data frames organise information into table-like columns.

11. Practical Exercise

Open RStudio and complete the following activities:

  1. Create a vector containing the numbers 20, 30, 40, 50, and 60.
  2. Create a vector containing the names of five Nigerian cities.
  3. Create a list containing your name, age, and examination score.
  4. Create a matrix containing the numbers 1 to 12, with three rows and four columns.
  5. Create an array with two rows, two columns, and two layers.
  6. Create a data frame containing five students, their ages, classes, and scores.
  7. Create a factor containing the categories JSS 1, JSS 2, and JSS 3.
  8. Use table() to count how many times each class appears.

12. Module Summary

In this module, you learned that data structures help R organise and store information.

  • Vectors store multiple values of the same basic data type.
  • Lists can store different types of information together.
  • Matrices organise same-type data into rows and columns.
  • Arrays organise same-type data across multiple dimensions.
  • Data frames organise information into table-like rows and columns.
  • Factors store categorical information.

Understanding these data structures is important because you will use them regularly when working with real datasets.

What Is Next?

In Module 5, we will learn how to import and explore data in R. You will discover how to bring CSV and Excel files into R, view datasets, inspect rows and columns, and understand the information inside a dataset before analysing it.

Keep practising! Learning how to organise data is an important step towards becoming a good data analyst.

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