Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← R for Data Analysis Expert · Lesson 12 of 17

Module Eleven

📖 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.
12
Module 11 · R for Data Analysis · Data Import and Export

Module 11 · Data Import and Export – Reading and Writing Files

Hello, young data explorer! In Module 10, we learned how to reshape data using tidyr. But where does data come from? Usually, data is stored in files on your computer. These files can be in many formats: CSV (comma-separated values), Excel, or even databases.

In this module, we will learn how to import (read) data into R from different file types, and export (write) data from R to files. This is like opening a book (reading) and writing your own book (saving). We will use packages like readr, readxl, and haven to handle different formats.

By the end of this module, you will be able to load any dataset into R and save your results for sharing. You will be a data librarian!


Learning Objectives

  • Understand why we need to import and export data.
  • Identify common file formats (CSV, Excel, text, etc.).
  • Install and load the readr package.
  • Use read_csv() to read CSV files.
  • Use write_csv() to write CSV files.
  • Install and load the readxl package.
  • Use read_excel() to read Excel files.
  • Learn about other formats: read_delim(), read_table().
  • Understand the working directory and file paths.
  • Apply these skills to real data, including Nigerian examples.

Warm-up Story: The Lost Data File

Chidi was doing a school project on Nigerian states. He had collected data in a CSV file on his computer. He opened R and typed read_csv("states.csv"), but R gave an error: "File not found." Chidi was confused. He realised he needed to tell R exactly where the file was on his computer – the path. He set his working directory to the folder containing the file, and it worked!

Later, he analysed the data and created a summary. He wanted to share his results with his teacher, so he used write_csv() to save the summary as a new CSV file. He emailed it to his teacher. Chidi learned that importing and exporting data is like opening and saving files – it's essential for working with real data.


Main Lessons

Lesson 1: What is Data Import and Export?

Definition: Import means reading data from a file into R. Export means writing data from R to a file.

Why it is important: Data lives in files (CSV, Excel, etc.). To analyse it, we must bring it into R. After analysis, we save results for sharing.

Simple explanation: It's like reading a book (import) and writing your own book (export).

Real-life example: A shopkeeper reads a price list from a spreadsheet (import) and writes a sales report (export).

School example: Your teacher reads a class list from a file (import) and saves grades (export).

Home example: You open a recipe from a file (import) and save your grocery list (export).

Nigerian example: A researcher reads population data from a CSV (import) and saves a summary report (export).

Illustration:

   File (on computer)  ----Import--->  R (data frame)
   R (data frame)       ----Export--->  File (saved)

Mini summary: Import = read into R; Export = save from R.


Lesson 2: Common File Formats

Definition: File formats are ways of storing data. Common ones are:

  • CSV (Comma-Separated Values): text file with commas.
  • Excel (.xlsx, .xls): spreadsheet files.
  • TSV (Tab-Separated Values): text file with tabs.
  • Text (.txt): plain text files.
  • RDS (.rds): R's own format.

Mini summary: CSV and Excel are most common for beginners.


Lesson 3: The Working Directory – Where R Looks for Files

Definition: The working directory is the folder where R looks for files.

Why it is important: If your file is not in the working directory, R won't find it.

Simple explanation: It's like the "home base" of your R session.

Real-life example: You keep your school books in a specific bag – you know where to find them.

School example: Your teacher tells you to open a file from the "Class Data" folder.

Home example: You keep your toys in a box – you know where to look.

Nigerian example: A researcher keeps all data files in a "Projects" folder.

Code:

   getwd()   # shows current working directory
   setwd("path/to/folder")  # changes it

Mini summary: Set your working directory to the folder containing your files.


Lesson 4: Reading CSV Files with readr

Definition: read_csv() is a function from the readr package that reads CSV files.

Why it is important: CSV is the most common data format.

Simple explanation: It's like opening a book – R reads the text and turns it into a table.

Real-life example: A scientist reads a CSV of weather data.

School example: A teacher reads a CSV of pupil scores.

Home example: You read a CSV of your family expenses.

Nigerian example: An economist reads a CSV of Nigeria's GDP data.

Code:

   install.packages("readr")
   library(readr)

   data <- read_csv("file.csv")
   # Or with a full path:
   data <- read_csv("C:/Users/YourName/Downloads/file.csv")

Illustration:

   CSV file (text):
   name,age,score
   Ade,10,85
   Bola,11,70

   read_csv() -> R data frame:
   +------+-----+-------+
   | name | age | score |
   +------+-----+-------+
   | Ade  | 10  | 85    |
   | Bola | 11  | 70    |
   +------+-----+-------+

Mini summary: read_csv() reads CSV files into R.


Lesson 5: Writing CSV Files with readr

Definition: write_csv() saves a data frame as a CSV file.

Why it is important: You can save your results and share them.

Simple explanation: It's like writing a story and saving it as a document.

Real-life example: A shop saves a sales summary as CSV.

School example: A teacher saves grades as CSV.

Home example: You save your chore chart as CSV.

Nigerian example: A researcher saves analysed data as CSV.

Code:

   write_csv(data, "output.csv")
   # Saves to working directory.

Mini summary: write_csv() saves data frames as CSV.


Lesson 6: Reading Excel Files with readxl

Definition: read_excel() from the readxl package reads Excel (.xlsx, .xls) files.

Why it is important: Excel is widely used in business and schools.

Simple explanation: It's like opening a spreadsheet in R.

Real-life example: A business reads an Excel budget file.

School example: A teacher reads an Excel attendance sheet.

Home example: You read an Excel list of family members.

Nigerian example: A government official reads an Excel file of state budgets.

Code:

   install.packages("readxl")
   library(readxl)

   data <- read_excel("file.xlsx")
   # Specify sheet if needed:
   data <- read_excel("file.xlsx", sheet = "Sheet1")

Mini summary: read_excel() reads Excel files.


Lesson 7: Writing Excel Files

To write Excel files, you can use the writexl package or openxlsx.

   install.packages("writexl")
   library(writexl)
   write_xlsx(data, "output.xlsx")

Mini summary: Use write_xlsx() to save as Excel.


Lesson 8: Reading Other Text Formats

Definition: read_delim() reads files with any separator (e.g., tabs, semicolons).

Real-life example: A tab-separated file.

School example: A file with pipe (|) separators.

Code:

   data <- read_delim("file.txt", delim = "\t")  # tab-separated
   data <- read_delim("file.txt", delim = ";")   # semicolon

Mini summary: read_delim() handles any delimiter.


Lesson 9: Handling File Paths

Definition: A file path tells R exactly where the file is located.

Why it is important: If you don't give the full path, R looks in the working directory.

Simple explanation: It's like giving an address to find a house.

Types:

  • Absolute path: full address (e.g., "C:/Users/Chidi/Data/file.csv")
  • Relative path: relative to working directory (e.g., "Data/file.csv")

Mini summary: Use full paths to avoid errors.


Lesson 10: Importing Data from the Web

You can read data directly from a URL.

   data <- read_csv("https://example.com/data.csv")

Mini summary: read_csv() works with web URLs too.


Lesson 11: Exporting Data for Sharing

After analysis, you might want to save your data in different formats.

   write_csv(data, "clean_data.csv")
   write_xlsx(data, "clean_data.xlsx")
   write_rds(data, "clean_data.rds")  # R's native format

Mini summary: Save your data in the format your audience needs.


Lesson 12: Reading Data from Databases

Definition: Databases are organised collections of data. R can connect to them using packages like DBI and odbc.

For beginners, we focus on files.

Mini summary: Databases are more advanced – we'll start with files.


Lesson 13: Common Errors and Solutions

  • File not found: Check the working directory or use full path.
  • Wrong separator: Use read_delim() with correct delim.
  • Header issues: Use col_names = TRUE or skip.
  • Encoding problems: Use locale() to specify encoding.

Mini summary: Most errors are due to file location or format.


Lesson 14: Real Nigerian Example – Importing Data

Let's say we have a CSV file "nigeria_population.csv" with columns: State, Population, Region.

   pop <- read_csv("nigeria_population.csv")
   head(pop)

Mini summary: Import Nigerian data easily with read_csv().


Lesson 15: Summary of Import/Export

We learned to read and write CSV, Excel, and other formats. We also learned about working directories and file paths.


Key Vocabulary

Import
Reading data into R from a file.
Export
Writing data from R to a file.
CSV
Comma-Separated Values – a text file format.
Excel
A spreadsheet file format (.xlsx).
Working Directory
The folder where R looks for files.
File Path
The location of a file on your computer.
readr
Package for reading text files.
readxl
Package for reading Excel files.

Important Concepts

  • Working directory is the default folder for files.
  • CSV is the most common data exchange format.
  • read_csv() is faster and better than base R's read.csv().
  • Relative paths are easier to use in projects.
  • Always check that your data imported correctly with head() or glimpse().

Step-by-Step Explanations

How to import a CSV file:

  1. Install readr: install.packages("readr").
  2. Load it: library(readr).
  3. Set working directory or use full path.
  4. Use read_csv("filename.csv").
  5. Assign to a variable: data <- read_csv("filename.csv").
  6. Check with head(data).

How to export a CSV:

  1. Prepare your data frame.
  2. Use write_csv(data, "output.csv").
  3. Check your working directory for the file.

Real-life Examples

  • A scientist reads weather data from a CSV file.
  • A teacher exports grades to Excel for the principal.
  • A shop imports inventory from a CSV.

Nigerian Examples

  • A researcher reads population data from NBS (National Bureau of Statistics) CSV files.
  • A student imports educational data from an Excel file.
  • A government analyst exports budget data to CSV for sharing.

Fun Examples Children Relate To

  • Read a CSV of your favourite cartoon characters and their ratings.
  • Export a list of your friends' birthdays to Excel.
  • Import a text file with your homework assignments.

Everyday Examples

  • You read a recipe from a text file.
  • You save a list of your chores to a CSV.
  • You open a spreadsheet of your savings.

Teacher Notes

  • Emphasise the importance of the working directory.
  • Show how to use relative paths with R projects.
  • Provide sample CSV files for practice.
  • Encourage students to explore file structures.

Parent Tips

  • Help your child create a folder for R projects.
  • Practice importing and exporting simple files together.
  • Discuss the importance of file organisation.

Interesting Facts

  • The CSV format has been around since the 1970s.
  • Excel files can contain multiple sheets.
  • R can read data from ZIP files directly.

Did You Know?

  • You can read data from Google Sheets into R using the googlesheets4 package.
  • R can read JSON and XML files too.
  • readr is part of the tidyverse.

Remember This

  • Always set your working directory or use full paths.
  • Use read_csv() for CSV files, read_excel() for Excel.
  • Check your imported data with head().
  • Save results with write_csv() or write_xlsx().

Common Mistakes

  • Forgetting to install/load the required package.
  • Using read.csv() instead of read_csv() (both work, but read_csv is faster).
  • Not specifying the full path when the file is not in the working directory.
  • Using the wrong separator (e.g., read_csv() for tab-separated files).
  • Not checking if the import was successful.

Best Practices

  • Use R projects to manage working directories automatically.
  • Store data files in a subfolder (e.g., "data/") to keep projects tidy.
  • Use readr functions for better performance.
  • Always specify the col_types argument for large files.
  • Document your data sources.

ASCII Illustrations

Import process

   File on disk  ----read_csv---->  R data frame
   (data.csv)                        (data)

Export process

   R data frame  ----write_csv---->  File on disk
   (data)                            (output.csv)

Comparison Tables

Import Functions
File TypeFunctionPackage
CSVread_csv()readr
Excelread_excel()readxl
Tab-separatedread_delim(file, delim = "\t")readr
RDSreadRDS()base R

End-of-Module Summary

In this module, we learned how to import (read) data from files into R and export (write) data from R to files. We used read_csv() and write_csv() for CSV files, and read_excel() for Excel files. We also learned about the working directory, file paths, and common errors. These skills are essential because most data comes from files, and we need to share our results.


Frequently Asked Questions

1. What is the difference between import and export?
Import reads data into R; export writes data from R.
2. What is a CSV file?
A text file with comma-separated values.
3. What package reads CSV files?
readr.
4. What package reads Excel files?
readxl.
5. What is the working directory?
The folder where R looks for files.
6. How do I check my working directory?
getwd().
7. How do I set my working directory?
setwd("path").
8. What is a file path?
The location of a file on your computer.
9. Can I read data from the internet?
Yes, read_csv("http://example.com/data.csv").
10. How do I save a data frame as CSV?
write_csv(data, "filename.csv").

Review Questions

  1. What is the difference between import and export?
  2. What is a CSV file?
  3. Which function reads CSV files?
  4. Which package reads Excel files?
  5. What is the working directory?
  6. How do you set the working directory?
  7. How do you save a data frame as CSV?
  8. What is a file path?
  9. What is the difference between absolute and relative paths?
  10. How do you check if a file was imported correctly?
  11. Can you read Excel files with readr?
  12. What is the delimiter in a CSV file?
  13. What does read_delim() do?
  14. What is an RDS file?
  15. Why is it important to set the working directory?

Fill-in-the-Blank Exercises

  1. ______ means reading data into R. (Import)
  2. ______ means writing data from R. (Export)
  3. ______ stands for Comma-Separated Values. (CSV)
  4. ______ is a package for reading CSV files. (readr)
  5. ______ is a package for reading Excel files. (readxl)
  6. The ______ is the folder where R looks for files. (working directory)
  7. Use ______ to set the working directory. (setwd)
  8. Use ______ to save a data frame as CSV. (write_csv)
  9. Use ______ to read an Excel file. (read_excel)
  10. A ______ is the location of a file on your computer. (file path)

True or False Exercises

  1. Import means writing data from R. (False)
  2. CSV files are text files. (True)
  3. read_csv() is from the readxl package. (False)
  4. read_excel() reads Excel files. (True)
  5. The working directory is the folder where R looks for files. (True)
  6. write_csv() saves data as Excel. (False)
  7. You can read files from the web. (True)
  8. RDS is an R-specific file format. (True)
  9. You don't need to check imported data. (False)
  10. A file path tells R where a file is. (True)

Multiple Choice Questions

  1. Which function reads CSV files?
    A. read_excel B. read_csv C. read_delim D. read_table
    Answer: B
  2. Which package is used for reading CSV files?
    A. readxl B. readr C. dplyr D. tidyr
    Answer: B
  3. Which package is used for reading Excel files?
    A. readr B. readxl C. dplyr D. tidyr
    Answer: B
  4. What is the separator in a CSV file?
    A. Tab B. Comma C. Semicolon D. Space
    Answer: B
  5. How do you set the working directory?
    A. getwd() B. setwd() C. dir() D. path()
    Answer: B
  6. How do you check the working directory?
    A. getwd() B. setwd() C. dir() D. path()
    Answer: A
  7. Which function writes a CSV file?
    A. write_excel B. write_csv C. write_delim D. write_table
    Answer: B
  8. What is a file path?
    A. The name of a file B. The location of a file C. The content of a file D. The size of a file
    Answer: B
  9. Can you read a file from a URL?
    A. Yes B. No C. Only with Excel D. Only with CSV
    Answer: A
  10. What is an RDS file?
    A. An Excel file B. A CSV file C. An R-specific file D. A text file
    Answer: C
  11. Which function reads tab-separated files?
    A. read_csv B. read_excel C. read_delim D. read_table
    Answer: C
  12. What does head() do?
    A. Shows the last rows B. Shows the first rows C. Shows the structure D. Shows the summary
    Answer: B
  13. Why is the working directory important?
    A. It saves files B. It tells R where to look for files C. It deletes files D. It changes file formats
    Answer: B
  14. What is the extension for CSV files?
    A. .txt B. .csv C. .xlsx D. .rds
    Answer: B
  15. Which package is part of the tidyverse?
    A. readxl B. readr C. both D. neither
    Answer: C

Matching Exercises

FunctionFile Type
1. read_csvA. Excel
2. read_excelB. CSV
3. read_delimC. Any delimiter
4. write_csvD. Save as CSV

Answers: 1-B, 2-A, 3-C, 4-D


Short Answer Questions

  1. What is the purpose of importing data?
  2. Explain the difference between CSV and Excel files.
  3. How do you set the working directory in R?
  4. What is the difference between absolute and relative paths?
  5. Why should you check your imported data?

Scenario-based Exercises

  1. Scenario: You have a CSV file "grades.csv" in your Downloads folder. You try to read it with read_csv("grades.csv") but get an error. What might be the problem?
  2. Scenario: You want to share your analysis results with a teacher who uses Excel. How would you save your results?
  3. Scenario: You have a tab-separated file. Which function would you use to read it?

Group Activity

In groups, create a small dataset (e.g., favourite foods with ratings). Save it as a CSV file. Then, each group member imports it into R and creates a summary. Export the summary as a new CSV file and share it with the group.


Individual Activity

Find a CSV file online (e.g., from a data portal). Import it into R, explore it with glimpse() and head(), and then save a filtered version as a new CSV file.


Classroom Discussion Questions

  1. Why is it important to organise files and folders?
  2. What are the advantages of using CSV over Excel?
  3. How would you import data from a website?
  4. What would you do if your file import fails?

Mini Project

Title: "Importing and Analysing Nigerian Data"
Find a CSV or Excel file about Nigeria (e.g., population, education, or weather). Import it into R, perform some basic analysis (summary, filtering), and export the results as a new file. Write a short report on what you found.


Practical Assignment

Using the iris dataset, save it as a CSV file using write_csv(). Then, import it back into R and verify it matches the original. Do the same with an Excel file using write_xlsx().


Challenge Exercise

Find a dataset in a format other than CSV (e.g., JSON, XML) and use appropriate R packages (e.g., jsonlite) to import it. Write a brief explanation of the process.


Quiz Answers

Fill-in-the-Blank: 1. Import, 2. Export, 3. CSV, 4. readr, 5. readxl, 6. working directory, 7. setwd, 8. write_csv, 9. read_excel, 10. file path.

True/False: 1F, 2T, 3F, 4T, 5T, 6F, 7T, 8T, 9F, 10T.

Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6A, 7B, 8B, 9A, 10C, 11C, 12B, 13B, 14B, 15C.


Key Takeaways

  • Import = read data into R; Export = save data from R.
  • CSV is the most common format; use read_csv().
  • Excel files use read_excel().
  • Always set your working directory or use full paths.
  • Check your data with head() after import.
  • Use write_csv() to save your results.

Preparation for the Next Module

In Module 12, we will learn about data cleaning – handling missing values, outliers, and inconsistencies in detail. We will combine skills from Modules 8-11 to create a complete data cleaning workflow. Practise importing and exporting data, and think about how you would clean messy data.


🏆 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.
→