In the previous module, we learned about vectors, lists, matrices, arrays, data frames, and factors in R. These structures help us organise information when working with data.
But what happens when you have hundreds or thousands of records saved in an Excel or CSV file? Do you need to type everything into R one by one? No!
R allows you to import data directly from files and explore the information before analysing it. This process is called data importing and exploration.
Data importing means bringing information from an external file into R so that you can work with it.
For example, imagine a supermarket in Ibadan has a file containing the following sales records:
| Product | Quantity | Price | City |
|---|---|---|---|
| Rice | 5 | 8000 | Ibadan |
| Beans | 3 | 4500 | Lagos |
| Garri | 4 | 3000 | Ibadan |
| Vegetable Oil | 2 | 6000 | Abuja |
Instead of typing every record into R, the supermarket can save the information in a CSV or Excel file and import it directly.
Before exploring a dataset, you should understand two important terms:
In a student results dataset, each row may represent one student, while the columns may contain the student's name, age, class, and examination score.
CSV means Comma-Separated Values. It is a common file format used to store information in rows and columns. CSV files can be opened with Excel, Notepad, and other applications.
R has a built-in function called read.csv() that allows you to import CSV files.
Imagine you have a file called students.csv.
students <- read.csv("students.csv")
print(students)
Let's understand the code:
read.csv() reads information from a CSV file."students.csv" is the name of the file.students is the variable where R stores the imported data.print(students) displays the imported records.
Another way to import CSV files is by using the readr package.
This package is part of the tidyverse collection of R tools.
install.packages("readr")
library(readr)
students <- read_csv("students.csv")
print(students)
You only need to install a package once. After installation, use library(readr)
whenever you start a new R session and want to use it.
Many businesses, schools, and organisations store their information in Microsoft Excel.
R can also import Excel files using a package called readxl.
First, install and load the package:
install.packages("readxl")
library(readxl)
Now import an Excel file called school_results.xlsx:
results <- read_excel("school_results.xlsx")
print(results)
If your Excel file contains several worksheets, you can select a particular worksheet by name:
results <- read_excel("school_results.xlsx", sheet = "Sheet1")
Remember that read_excel() comes from the readxl package.
You must install and load the package before using it.
R needs to know where your file is saved before it can import it. This location is called the file path.
For example, if your file is saved inside a folder called Data on your computer, its location might be:
"C:/Users/Student/Documents/Data/students.csv"
You can import the file using its full path:
students <- read.csv("C:/Users/Student/Documents/Data/students.csv")
You can also check the current working directory using:
getwd()
The working directory is the folder R currently uses when looking for files.
You can change it with setwd():
setwd("C:/Users/Student/Documents/Data")
After changing the working directory, you can import the file using only its name:
students <- read.csv("students.csv")
Beginner tip: You can also use RStudio's Import Dataset option to select a file
through a graphical window instead of typing its file path.
Another option is file.choose(), which opens a file-selection window:
students <- read.csv(file.choose())
Importing data is only the first step. You must also inspect the information to understand what it contains.
R provides several useful functions for exploring datasets.
The head() function displays the first six rows of a dataset by default.
head(students)
You can display the first ten rows by writing:
head(students, 10)
The tail() function displays the last six rows of a dataset by default.
tail(students)
The str() function shows the structure of a dataset.
It helps you understand the column names and the types of information stored in them.
str(students)
The summary() function provides a quick statistical summary of the dataset.
For numerical columns, it can display the minimum, maximum, median, mean, and quartiles.
summary(students)
The dim() function tells you how many rows and columns a dataset contains.
dim(students)
For example, if R returns 100 5, the dataset has 100 rows and 5 columns.
The names() function displays the names of all columns in a dataset.
names(students)
These functions help you count the rows and columns separately.
nrow(students)
ncol(students)
Sometimes, you may not need the entire dataset. You may want to examine only a particular row or column.
For example, imagine your dataset contains these columns:
To display only the Name column, use:
students$Name
To display the first five rows and all columns, use:
students[1:5, ]
To display all rows but only the first column, use:
students[, 1]
To display the first five rows of the second column, use:
students[1:5, 2]
Remember that R starts counting positions from 1, not 0. This means the first row is row 1 and the first column is column 1.
Let's create a small dataset containing the names and examination scores of five students. We will use it to practise exploring data in R.
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)
# Display the first rows
head(students)
# Check the dataset structure
str(students)
# Get a statistical summary
summary(students)
# Count the number of rows
nrow(students)
# Count the number of columns
ncol(students)
# Display only student scores
students$Score
From this example, you can discover:
Beginners sometimes experience errors when importing files. Here are some common problems and their solutions:
| Problem | Possible Solution |
|---|---|
| File not found | Check the file name and location. |
| Package not found | Install the required package and load it with library(). |
| Wrong file extension | Check whether the file is CSV or Excel. |
| Unexpected column names | Check the first row of the file to confirm its headers. |
| Incorrect data types | Inspect the dataset using str() and check how the values were imported. |
Imagine you are helping a school in Ibadan analyse its students' examination results.
Your teacher gives you a file called exam_results.csv.
Complete the following tasks using R:
In this module, you have learned how to:
read.csv() and read_csv().read_excel().head(), tail(), str(), and summary().nrow() and ncol().Now that you know how to import and explore datasets, it is time to learn how to prepare information for analysis.
In the next module, Data Cleaning and Transformation in R, you will learn how to identify missing values, remove duplicate records, correct errors, and organise information using R.