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!
readr package.read_csv() to read CSV files.write_csv() to write CSV files.readxl package.read_excel() to read Excel files.read_delim(), read_table().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.
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.
Definition: File formats are ways of storing data. Common ones are:
Mini summary: CSV and Excel are most common for beginners.
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.
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.
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.
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.
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.
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.
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:
Mini summary: Use full paths to avoid errors.
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.
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.
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.
read_delim() with correct delim.col_names = TRUE or skip.locale() to specify encoding.Mini summary: Most errors are due to file location or format.
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().
We learned to read and write CSV, Excel, and other formats. We also learned about working directories and file paths.
read.csv().head() or glimpse().readr: install.packages("readr").library(readr).read_csv("filename.csv").data <- read_csv("filename.csv").head(data).write_csv(data, "output.csv").googlesheets4 package.readr is part of the tidyverse.read_csv() for CSV files, read_excel() for Excel.head().write_csv() or write_xlsx().read.csv() instead of read_csv() (both work, but read_csv is faster).read_csv() for tab-separated files).readr functions for better performance.col_types argument for large files.File on disk ----read_csv----> R data frame (data.csv) (data)
R data frame ----write_csv----> File on disk (data) (output.csv)
| File Type | Function | Package |
|---|---|---|
| CSV | read_csv() | readr |
| Excel | read_excel() | readxl |
| Tab-separated | read_delim(file, delim = "\t") | readr |
| RDS | readRDS() | base R |
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.
readr.readxl.getwd().setwd("path").read_csv("http://example.com/data.csv").write_csv(data, "filename.csv").read_delim() do?head() do?| Function | File Type |
|---|---|
| 1. read_csv | A. Excel |
| 2. read_excel | B. CSV |
| 3. read_delim | C. Any delimiter |
| 4. write_csv | D. Save as CSV |
Answers: 1-B, 2-A, 3-C, 4-D
read_csv("grades.csv") but get an error. What might be the problem?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.
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.
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.
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().
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.
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.
read_csv().read_excel().head() after import.write_csv() to save your results.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.