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.
By the end of this module, you should be able to:
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:
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.
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.
You can also create a vector containing text values.
students <- c("Ade", "Chika", "Tunde", "Fatima", "Emeka")
print(students)
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
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.
A list is a data structure that can store different types of information together.
For example, a student's record may contain:
These values have different data types. A list allows you to store them together.
student <- list( name = "Ade", age = 13, score = 85, passed = TRUE ) print(student)
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.
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.
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.
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.
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.
sales <- array( 1:12, dim = c(2, 3, 2) ) print(sales)
This creates an array with:
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.
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.
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 |
|---|---|---|---|
| Ade | 13 | JSS 2 | 75 |
| Chika | 14 | JSS 3 | 85 |
| Tunde | 13 | JSS 2 | 60 |
| Fatima | 14 | JSS 3 | 90 |
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.
students[1, ]
This displays the first student's complete record.
students[, "score"]
This displays the score column.
nrow(students) ncol(students) dim(students)
These commands help you find the number of rows, columns, and overall dimensions of your dataset.
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.
student_class <- factor(
c("JSS 1", "JSS 2", "JSS 1", "JSS 3", "JSS 2")
)
print(student_class)
You can use the levels() function to see the categories stored in a factor.
levels(student_class)
R displays the available categories.
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.
| 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 |
Imagine you are helping a school in Ibadan organise its students' examination results.
You have the following information:
| Name | Age | Class | Score |
|---|---|---|---|
| Ade | 13 | JSS 2 | 75 |
| Chika | 14 | JSS 3 | 85 |
| Tunde | 13 | JSS 2 | 60 |
| Fatima | 14 | JSS 3 | 90 |
| Emeka | 13 | JSS 2 | 70 |
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.
Open RStudio and complete the following activities:
In this module, you learned that data structures help R organise and store information.
Understanding these data structures is important because you will use them regularly when working with real datasets.
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.