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

Module Five

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

Module 5: Importing and Exploring Data in R

1. Introduction

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.

2. What Is Data Importing?

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
Rice58000Ibadan
Beans34500Lagos
Garri43000Ibadan
Vegetable Oil26000Abuja

Instead of typing every record into R, the supermarket can save the information in a CSV or Excel file and import it directly.

3. Understanding Rows and Columns

Before exploring a dataset, you should understand two important terms:

  • Rows: These represent individual records or observations.
  • Columns: These represent the different types of information or variables.

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.

4. Importing CSV Files into R

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.

Example: Importing a Student Records File

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.

Using the readr Package

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.

5. Importing Excel Files into R

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.

6. Understanding File Locations

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())

7. Exploring Imported Data

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.

A. head()

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)

B. tail()

The tail() function displays the last six rows of a dataset by default.

tail(students)

C. str()

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)

D. summary()

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)

E. dim()

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.

F. names()

The names() function displays the names of all columns in a dataset.

names(students)

G. nrow() and ncol()

These functions help you count the rows and columns separately.

nrow(students)

ncol(students)

8. Selecting Specific Rows and Columns

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:

  • Name
  • Age
  • Class
  • Score

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.

9. Practical Example: Exploring Student Results

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:

  • How many students are in the dataset.
  • The examination score of each student.
  • The average and highest examination scores.
  • The type of information stored in each column.

10. Common Problems When Importing Data

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.

11. Practical Exercise

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:

  1. Import the CSV file into R.
  2. Display the first six records.
  3. Display the last six records.
  4. Check the structure of the dataset.
  5. Display a summary of the information.
  6. Count the number of rows and columns.
  7. Display only the examination score column.

12. Module Summary

In this module, you have learned how to:

  • Understand data importing and exploration.
  • Import CSV files using read.csv() and read_csv().
  • Import Excel files using read_excel().
  • Understand file paths and working directories.
  • Explore datasets using head(), tail(), str(), and summary().
  • Count rows and columns using nrow() and ncol().
  • Select specific rows and columns from a dataset.

13. What Is Next?

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.

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