Back to Course
Data I/O

Importing and Exporting Data

Analysis starts with getting data into R and ends with getting results out. This lesson covers the most common formats: CSV, Excel, databases, and web APIs.

1. Reading and Writing CSV Files

Base R provides read.csv(), but the readr package (part of tidyverse) is faster and more consistent:

# Base R
df <- read.csv("data/sales.csv")
write.csv(df, "data/output.csv", row.names = FALSE)

# readr (tidyverse) — recommended
library(readr)
df <- read_csv("data/sales.csv")
write_csv(df, "data/output.csv")
Pro Tip: read_csv() from readr is faster, guesses column types more reliably, and never silently converts strings to factors — prefer it over base R's read.csv().

2. Working with Excel Files

Use the readxl package to import .xlsx/.xls files, and writexl or openxlsx to export:

install.packages(c("readxl", "writexl"))
library(readxl)
library(writexl)

df <- read_excel("data/report.xlsx", sheet = "Sheet1")
excel_sheets("data/report.xlsx")   # list all sheet names

write_xlsx(df, "data/output.xlsx")

3. Connecting to Databases

R connects to relational databases using the DBI package with a database-specific driver (e.g., RSQLite, RPostgres, RMySQL).

install.packages(c("DBI", "RSQLite"))
library(DBI)

con <- dbConnect(RSQLite::SQLite(), "data/mydb.sqlite")
dbListTables(con)

result <- dbGetQuery(con, "SELECT * FROM customers WHERE age > 30")

dbDisconnect(con)

For PostgreSQL or MySQL, the pattern is nearly identical — swap the driver:

con <- dbConnect(RPostgres::Postgres(),
                  dbname = "mydb", host = "localhost",
                  port = 5432, user = "admin", password = "secret")
Common Issues: Never hardcode database passwords in scripts. Use environment variables or the keyring package, especially in shared or version-controlled projects.

4. Pulling Data from APIs

The httr2 (or older httr) package handles HTTP requests, and jsonlite parses JSON responses.

install.packages(c("httr2", "jsonlite"))
library(httr2)
library(jsonlite)

resp <- request("https://api.example.com/users") |>
  req_headers(Authorization = "Bearer YOUR_TOKEN") |>
  req_perform()

data <- resp |> resp_body_json(simplifyVector = TRUE)
head(data)

5. Comparing Import Methods

SourcePackageKey Function
CSVreadrread_csv() / write_csv()
Excelreadxl / writexlread_excel() / write_xlsx()
SQL DatabaseDBI + driverdbConnect() / dbGetQuery()
Web API (JSON)httr2 + jsonlitereq_perform() / resp_body_json()

6. Production-Ready Checklist

  • ✅ Use readr for CSVs — faster and more predictable than base R.
  • ✅ Use readxl/writexl for Excel — no need for Excel to be installed.
  • ✅ Use DBI + driver packages for databases — always close connections with dbDisconnect().
  • ✅ Secure API credentials — never commit tokens or passwords to source control.
Pro Tip: Always inspect imported data immediately with str(), head(), and summary() — catching type or encoding issues early saves hours of debugging downstream.

Ready to master R Programming?

Build real-world data analysis and visualization projects with hands-on training, mentor-led sessions, and placement support.

Explore Course