Learn tidyverse · 2/13

Data Ingestion: Bringing Data into R (readr & friends)

7 min read

Data Ingestion: Bringing Data into R (readr & friends)

👋 Introduction

Welcome to the dining room of data science! 🍽️

Right now, your R environment is likely empty. It’s a clean slate, which is peaceful, but you can’t analyze specific data if you don't have any loaded. R is incredibly powerful, but without external data, it's just a very sophisticated calculator.

Data Ingestion is the process of importing data from external sources (like text files, spreadsheets, or databases) into your R workspace so you can manipulate and analyze it.

In the tidyverse, we primarily use the readr package for flat files and readxl for Excel spreadsheets. These packages are designed to be fast, friendly, and consistent.


🛠️ Setup

Before we start eating, we need to set the table. Ensure you have the tidyverse installed and loaded.

r
# If you haven't installed it yet:
# install.packages("tidyverse")

# Load the core tidyverse packages (includes readr)
library(tidyverse)

Note: While readr is loaded automatically with library(tidyverse), the package readxl (for Excel files) is installed with the tidyverse bundle but must be loaded explicitly if you need it.


1. Reading Flat Files: read_csv and the readr Family

Definition

A Flat File is a plain text file where each line usually represents a row of data, and values within that row are separated by a specific character (delimiter).

  • CSV (Comma Separated Values): Separated by commas (,). The industry standard.
  • TSV (Tab Separated Values): Separated by tabs.

The Problem

You have a file named sales_data.csv on your computer. You need to turn that text file into an R data frame (specifically, a tibble) to calculate the average sales.

The Solution: read_csv()

The readr package provides read_csv().

Wait, isn't there a read.csv() in base R?
Yes, but read_csv() (with an underscore) is generally preferred in the tidyverse because:

  1. Speed: It is up to 10x faster than base R.
  2. Tibbles: It reads data directly into a tibble (modern data frame), which doesn't accidentally print 10,000 rows to your console.
  3. No Factors: It doesn't automatically convert text strings into factors (a common source of headaches in base R).

Hands-on Example

Since I cannot put a file on your hard drive, we will use a raw string to simulate reading a file. In real life, you would put a file path like "data/my_file.csv" inside the quotes.

r
# Simulating a CSV file named "students.csv"
csv_data <- "
Name,Age,Grade
Alice,20,88.5
Bob,22,91.0
Charlie,21,79.5
"

# Reading the data
students <- read_csv(csv_data)

# Print the result
print(students)

Output:

text
# A tibble: 3 × 3
  Name      Age Grade
  <chr>   <dbl> <dbl>
1 Alice      20  88.5
2 Bob        22  91.0
3 Charlie    21  79.5

🧠 Industry Best Practice: Relative Paths

When reading files, beginners often use paths like:
"C:/Users/JohnDoe/Documents/Project/data.csv" (Absolute Path).
Don't do this. If you send your code to a colleague, their name isn't JohnDoe, and the code will break.

Use R Projects and relative paths:
"data/data.csv"
This looks for the folder data inside your current project folder.

Other Members of the Family

  • read_tsv(): For tab-separated files.
  • read_delim(): If you have a weird file separated by semi-colons (;) or pipes (|), you can specify the delimiter: read_delim("file.txt", delim = "|").

2. Column Specification: Controlling Data Types

The Problem

Imagine you have a dataset of Employee IDs. One ID is 00456.
If readr looks at that, it thinks, "Ah, numbers! I will save this as the number 456."
Result: You lost the leading zeros. The ID is now wrong.

How readr Guesses

Under the hood, readr reads the first 1,000 rows of your file and guesses the type (Logical, Integer, Double, Character, etc.) based on what it sees.

  • If it sees only numbers -> Double.
  • If it sees numbers and letters -> Character.

Sometimes, the guess is wrong (e.g., the first 1000 rows are empty, but row 1001 has text).

The Solution: The col_types argument

You can explicitly tell R what data type each column should be.

Hands-on Example

Let's force an "ID" column to be character (text) so we keep the leading zeros.

r
# A dataset where ID looks like a number, but acts like a code
employee_data <- "
EmployeeID,Name,HiredDate
00123,Sarah,2023-01-15
00456,Mike,2023-02-20
"

# Specifying column types
# 'c' = character, 'D' = Date
employees <- read_csv(
  employee_data,
  col_types = cols(
    EmployeeID = col_character(),
    Name = col_character(),
    HiredDate = col_date(format = "%Y-%m-%d")
  )
)

print(employees)

Output:

text
# A tibble: 2 × 3
  EmployeeID Name  HiredDate 
  <chr>      <chr> <date>    
1 00123      Sarah 2023-01-15
2 00456      Mike  2023-02-20

Common Type Collectors:

  • col_character(): Text.
  • col_double(): Numbers with decimals.
  • col_integer(): Whole numbers.
  • col_date(): Dates (ISO8601 preferred).
  • col_skip(): Don't import this column at all (saves memory!).

3. Dealing with Excel Files: An Intro to readxl

The Reality Check

As much as developers love CSVs, the business world runs on Excel (.xlsx or .xls). You will inevitably receive a dataset that is color-coded, has merged cells, and is located on "Sheet3".

The Setup

You must load this explicitly.

r
library(readxl)

The Solution: read_excel()

This function reads Excel files. It does not support writing to Excel (we usually write to CSV for that, or use a package like writexl or openxlsx).

Common Arguments

  1. path: Where the file is.
  2. sheet: Which sheet to read? You can use the name ("Sales 2023") or the index (2).
  3. skip: Excel reports often have titles in the first few rows (e.g., "CONFIDENTIAL REPORT") before the actual headers. Use skip to jump over them.

Hands-on Syntax

Assuming we have a file named quarterly_report.xlsx.

r
# Basic read of the first sheet
df <- read_excel("quarterly_report.xlsx")

# Reading a specific sheet and skipping the first 2 rows of "junk" header info
clean_df <- read_excel(
  "quarterly_report.xlsx", 
  sheet = "Q3_Data", 
  skip = 2
)

🤓 Fun Fact: Excel stores dates as "numbers of days since December 30, 1899". If you import an Excel file and your dates look like 44927, readxl usually handles this automatically, but CSV parsers will just show you the number!


4. Exporting Data: Saving Your Hard Work

The Problem

You’ve imported your dirty data, cleaned it, filtered it, and calculated new columns. Now you want to send the clean version to your boss or save it for a Tableau dashboard.

The Solution: write_csv()

This is the inverse of read_csv(). It saves a data frame to a delimited file on your computer.

Hands-on Example

r
# 1. Create a dummy dataset
processed_data <- tibble(
  Item = c("Apples", "Bananas"),
  Price = c(1.20, 0.80),
  In_Stock = c(TRUE, FALSE)
)

# 2. Write it to disk
# In real life, provide a path like "output/clean_prices.csv"
write_csv(processed_data, "clean_prices.csv")

Why use write_csv over write.csv?

  1. UTF-8 Encoding: write_csv defaults to UTF-8 encoding. This is crucial if your data contains special characters, accents, or emojis. Base R's write.csv depends on your operating system's default, which can break files when moving between Windows and Mac.
  2. ISO Dates: It writes dates in the ISO8601 standard (YYYY-MM-DD) so other software parses them correctly.
  3. No Row Names: Base R adds a column of row numbers (1, 2, 3...) by default. write_csv does not, because row names are generally considered bad practice in tidy data.

📚 References & Resources


🧪 Quick Challenge

  1. Create a folder in your computer.
  2. Save a CSV file there with a column of numbers that start with zero (like zip codes).
  3. Try to read it into R using read_csv() and ensure the zeros don't vanish!

Challenge

Challenge: Data Ingestion and Cleaning with readr

You have been given a raw string variable, sales_report_string, which contains sales data in CSV format. Your task is to correctly ingest this data into a tibble, ensuring data integrity, and then write the code to export the cleaned data.

Requirements:

  1. Use the readr::read_csv() function to parse the sales_report_string.
  2. During ingestion, you must specify the column types to prevent common parsing errors:
    • The product_id column contains leading zeros that are crucial for identification. Ensure this column is imported as a character/text type.
    • The sale_date column should be parsed directly into a date format.
    • The internal_notes column is irrelevant for analysis and should be skipped entirely during the import process.
  3. Assign the resulting cleaned data to a variable named sales_data.
  4. After creating the sales_data tibble, write a second line of code to export this tibble to a file named "cleaned_sales_data.csv" using readr::write_csv(). The output file should not contain an extra column for row numbers.

Expected result

The final code should consist of two primary R commands.

The first command defines the sales_data variable by calling read_csv() on the sales_report_string. This function call must include the col_types argument to correctly specify the column types. The col_types specification should look similar to this:

r
cols(
  product_id = col_character(),
  sale_date = col_date(format = ""),
  internal_notes = col_skip()
)

The second command should be a call to write_csv(), passing the sales_data tibble as the first argument and the string "cleaned_sales_data.csv" as the second argument.

r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.