Learn R Β· 6/15

Data Import and Export: Moving Data In and Out

8 min read

Data Import and Export: Moving Data In and Out 🚚

Welcome, data wrangler! So, you've decided to tame the wild beasts of data in R. Excellent choice! But before you can perform your data magic, you need to get the data into your R environment. Think of your R session as a pristine, organized kitchen. You can't cook a magnificent meal (i.e., analyze data) without first bringing in the groceries (your data). This guide is all about mastering the art of data transportation – getting it in and sending it out.

Let's be honest, data rarely just appears in R. It lives in spreadsheets, text files, databases, and all over the web. Our job is to build a reliable bridge between these outside sources and our R world. Messing this up is like trying to make a cake but accidentally grabbing salt instead of sugar – the results will be... unappetizing. So, let's learn to read the labels correctly!


πŸ“₯ Reading Flat Files: CSVs and TXTs (read.csv / readr)

Imagine you have a list of all the superheroes and their powers stored in a simple text file. Each piece of information is neatly separated by a comma. This, my friend, is a CSV (Comma-Separated Values) file, one of the most common ways to store data. It's like the plain vanilla ice cream of data formats – simple, universal, and gets the job done.

The Problem: How do we get this neatly organized data from a file on our computer into an R data frame so we can start analyzing it?

The Solution: R has built-in tools and specialized packages to handle this effortlessly.

Using read.csv from Base R

The read.csv() function is your trusty, built-in tool for reading CSV files. It's been part of R since the beginning and is straightforward to use.

Let's say you have a file named heroes.csv with the following content:

csv
name,power,level
Superman,Flight,100
Batman,Gadgets,90
Wonder Woman,Super Strength,95

To read this into R, you would use:

r
# Make sure your R session's working directory is where the file is!
# Or provide the full path to the file.
heroes_df <- read.csv("heroes.csv")
print(heroes_df)

What's Happening Under the Hood?

When you call read.csv(), R opens the file, reads it line by line, and uses the commas to figure out where one column ends and the next begins. It's smart enough to use the first line as the header (column names). One important thing it does by default is convert text columns (like name and power) into a special data type called a "factor". This can be useful for statistical modeling, but often, we want to keep them as plain text.

A Common Gotcha: The stringsAsFactors argument.

In older versions of R, read.csv() automatically converted strings to factors. This caused a lot of headaches for beginners. Imagine trying to add a new hero, and R throws a "new level" error because the "power" isn't a recognized category! To avoid this, it's good practice to explicitly set it to FALSE.

r
# The modern, safer way with base R
heroes_df <- read.csv("heroes.csv", stringsAsFactors = FALSE)

Newer versions of R have made this the default behavior, but it's a good habit to be explicit.

The readr Package: A Modern Approach πŸš€

The readr package, part of the Tidyverse, is a more modern and often faster alternative to base R's functions. It's like upgrading from a reliable old pickup truck to a sleek, new electric one. It's faster, has more features, and gives you more feedback.

Installation:
You'll need to install it first if you don't have the tidyverse package collection.

r
install.packages("readr")

Using read_csv()
Notice the underscore _ instead of a dot .! This is a Tidyverse convention.

r
library(readr) # Load the package

# read_csv is generally faster and smarter
heroes_df_modern <- read_csv("heroes.csv")
print(heroes_df_modern)

Why is read_csv() often better?

  • Speed: It's significantly faster for large files.
  • Intelligent Guessing: It's better at guessing the data type of each column (e.g., numeric, character, date). It will also print out its guesses so you can check.
  • No Factors by Default: It reads text as text (character vectors), which is usually what you want for data manipulation.
  • Reproducibility: It's more consistent across different computers and operating systems.

Fun Fact: The creator of readr, Hadley Wickham, is a bit of a legend in the R community. He's the chief scientist at RStudio (now Posit) and the mastermind behind the Tidyverse. Creating readr was a way to solve many of the common frustrations he and others had with data import in R.


πŸ“Š Importing Excel Spreadsheets with readxl

Ah, Excel. The tool that runs a good portion of the business world. Sooner or later, you're going to be handed an Excel file (.xls or .xlsx) and asked to do some analysis. Don't panic! You don't need to manually save every sheet as a CSV.

The Problem: How do we directly import data from an Excel spreadsheet, which might have multiple sheets and complex formatting, into R?

The Solution: The readxl package is your best friend for this task. It's also part of the Tidyverse family.

Installation:

r
install.packages("readxl")

Getting Started:

Imagine you have an Excel file named superhero_data.xlsx with a sheet named "Active Heroes".

r
library(readxl) # Load the package

# Specify the path to the Excel file and the sheet name
active_heroes <- read_excel("superhero_data.xlsx", sheet = "Active Heroes")
print(active_heroes)

Common Scenarios:

  • What if I don't know the sheet names? readxl has a handy function for that.
    r
    excel_sheets("superhero_data.xlsx")
  • What if the data doesn't start in the first row? Sometimes Excel files have titles or notes at the top. You can use the skip argument.
    r
    # Skips the first 3 rows
    read_excel("superhero_data.xlsx", sheet = "Active Heroes", skip = 3)
  • What if there are no column names? You can tell readxl your data has no header and then add them later.
    r
    read_excel("superhero_data.xlsx", col_names = FALSE)

readxl is fantastic because it has no external dependencies (like Java, which was a pain with older packages), making it easy to install and use. It just works!


🌐 Fetching Web Data: APIs and JSON files

The modern world runs on data, and a lot of that data is available on the internet through APIs (Application Programming Interfaces). An API is like a restaurant menu for a web service. You make a request (order a dish), and the API sends back the data you asked for (your food). A very common format for this data is JSON (JavaScript Object Notation).

The Problem: How do we ask a server on the internet for data and then parse the JSON response into a usable R data frame?

The Solution: We'll use a combination of two powerful packages: httr to talk to the web and jsonlite to understand the response.

A Real-World Scenario: Getting Data from a Joke API

Let's fetch a random programming joke from an API. Because who doesn't need a good laugh while debugging?

Installation:

r
install.packages("httr")
install.packages("jsonlite")

The Process:

  1. Make the Request: We use httr::GET() to send a request to the API's URL.
  2. Check the Response: Did it work? A "status code" of 200 means everything is okay!
  3. Parse the JSON: We take the raw content of the response and use jsonlite::fromJSON() to turn it into a neat R list or data frame.
r
library(httr)
library(jsonlite)

# The URL for the joke API
url <- "https://official-joke-api.appspot.com/random_joke"

# 1. Make the request
response <- GET(url)

# 2. Check the status
http_status(response) # Check for a "200 OK" status

# 3. Extract and parse the content
content_text <- content(response, "text")
joke_data <- fromJSON(content_text)

# Let's see our joke!
print(joke_data$setup)
print(joke_data$punchline)

What is JSON really?
JSON is a way of structuring data using key-value pairs, similar to R's named lists. It's lightweight and easy for both humans and machines to read.

A simple JSON object looks like this:

json
{
  "name": "Batman",
  "power": "Gadgets",
  "level": 90
}

fromJSON() is smart enough to convert this into a structure that R understands. This process of fetching data from APIs is fundamental to modern data science. You can get stock prices, weather data, social media trends, and so much more!


πŸ“€ Exporting Data: Saving Your Masterpiece

You've done it! You've imported your data, cleaned it, performed some amazing analysis, and now you have a final, beautiful dataset. You can't just leave it in your R session, which will vanish when you close it. You need to save your work.

The Problem: How do we save our R data frames to files that can be easily shared or used by other programs (like Excel)?

The Solution: Just like we have functions for reading data, we have functions for writing it.

Saving as a CSV file

The most common way to export data is to save it as a CSV file. The write.csv() function from base R or readr::write_csv() are perfect for this.

Using base R's write.csv():

r
# Let's assume you have a final data frame called 'final_analysis_df'
# write.csv(data_frame, "file_name.csv")

# A common gotcha: write.csv includes row numbers by default.
# Usually, you don't want these.
write.csv(final_analysis_df, "analysis_results.csv", row.names = FALSE)

Using readr's write_csv():
This is often preferred as it's faster and doesn't write row names by default.

r
library(readr)

write_csv(final_analysis_df, "analysis_results.csv")

And that's it! You've successfully exported your data. You can now email this CSV to a colleague, open it in Excel, or use it as an input for another process. You are the master of data logistics! πŸ“¦


πŸ“š Extra Reading & References

  • readr Documentation: The official documentation is a great place to learn about all the powerful options available.
  • readxl Documentation: For more advanced Excel importing techniques, check out the official readxl website.
  • httr Vignettes: Learn how to interact with web APIs in more detail.
  • Data Import/Export Chapter in "R for Data Science": A fantastic, in-depth guide that covers these topics and more.

Challenge

You are tasked with creating a data pipeline in R to fetch, combine, and prepare data for export from a public API.

  1. Load the necessary libraries for handling HTTP requests (httr), parsing JSON (jsonlite), and writing CSV files (readr).
  2. Send an HTTP GET request to the URL https://jsonplaceholder.typicode.com/users to retrieve a list of users.
  3. Parse the raw JSON content from the response into a data frame named users_df.
  4. Perform a second HTTP GET request to the URL https://jsonplaceholder.typicode.com/posts to retrieve a list of posts.
  5. Parse the raw JSON content from this second response into a data frame named posts_df.
  6. Combine the two data frames into a single data frame named merged_data. Use the id column from users_df and the userId column from posts_df as the keys for merging.
  7. Write the final line of code that would save the merged_data data frame to a CSV file named user_posts.csv. Use the function from the readr package.

Expected result

Your R script should contain the complete code to perform the following actions:

  1. Load the httr, jsonlite, and readr packages using the library() function.
  2. Use httr::GET() to fetch data from the two specified API endpoints.
  3. Use jsonlite::fromJSON() to correctly parse the content of each response into two distinct data frames (users_df and posts_df).
  4. Merge the two data frames into merged_data using a function like merge() with the correct by.x and by.y arguments.
  5. Include the correct readr::write_csv() function call to write the merged_data data frame to a file named user_posts.csv.
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.