🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

R Data Import and Export Across Files, APIs, and SQL

R BasicsData Import/ExportđŸŸĸ Free Lesson

R Data Import and Export Across Sources

R Basics

One interface for sources that have nothing in common

A CSV on disk, a worksheet, a REST endpoint, and a SQL table share almost nothing: different transports, different type systems, different failure modes. What they do share is the shape of the answer you want — a data frame, correct types, a known provenance — and that shared answer is worth designing for. Projects that treat every import as a one-off script end up with fifteen slightly different readers, each wrong in its own way, and no way to tell which one produced the number in the report.

The alternative is a thin import layer: one function per source family, each returning the same contract of typed columns plus metadata about what was read and what was skipped. Everything downstream then depends on the contract instead of on the quirks of a particular file.

  • Wrap each source family in a function that returns a typed data frame.
  • Record row counts, columns, and parse problems at the boundary.
  • Push filtering into databases and APIs rather than into memory.

Prerequisites

  • !R file handling with readr
  • !Working with functions and the pipe operator

What You'll Learn

  • 1Fetch and paginate through JSON web APIs with explicit error handling
  • 2Parse XML and HTML documents with XPath selectors
  • 3Read files larger than memory using chunked and fast readers
  • 4Write exports that the next tool in the chain can consume

Choosing a reader before writing any code

Format alone does not decide the reader; size, frequency, and the consumer of the result do. A one-off 40 KB file deserves read_csv(), a 12 GB nightly extract does not, and a column you will join on next week should be typed at import regardless of what the file looks like today.

SourceReaderReturnsChoose it when
CSV / TSV, smallreadr::read_csv()tibbleroutine loads, problems matter
CSV / TSV, hugedata.table::fread()data.tableone pass, gigabytes, speed is the constraint
Excelreadxl::read_excel()tibblehumans hand you spreadsheets
JSON file or URLjsonlite::fromJSON()list / data.framenested records, arrays of objects
XML / HTMLxml2::read_xml()documentyou need XPath, not string splitting
SQL tableDBI::dbGetQuery()data.framethe data already lives in a warehouse
HTTP APIhttr::GET()responsethe source pushes, paginates, or authenticates

Frequency matters as much as format. A source read once deserves readable code; a source read four hundred times a day deserves caching, retries, and a schema check that fails loudly before a single bad row reaches the warehouse.

Fetching web APIs without fragile code

HTTP clients fail in ways files never do: timeouts, rate limits, expired tokens, and payloads that change shape between pages. The pattern below makes each of those visible instead of silent, and the pagination loop is the part most scripts get wrong by accident.

library(httr)
library(jsonlite)
library(dplyr)

fetch_page <- function(base, page, token) {
  resp <- GET(
    base,
    query = list(page = page, per_page = 100),
    add_headers(Authorization = paste("Bearer", token)),
    timeout(30)
  )

  stop_for_status(resp)          # raises a clear error on 4xx / 5xx
  content(resp, "parsed", type = "application/json")
}

fetch_all <- function(base, token, max_pages = 50) {
  out <- list()
  for (page in seq_len(max_pages)) {
    payload <- fetch_page(base, page, token)
    if (!length(payload$items)) break
    out[[page]] <- bind_rows(payload$items)
    if (!length(payload$links$next)) break
  }
  bind_rows(out)
}

events <- fetch_all("https://api.example.com/v1/events", Sys.getenv("EVENTS_TOKEN"))

# The contract: what did we actually bring back?
stopifnot(all(c("id", "created_at", "type") %in% names(events)))
nrow(events)

stop_for_status() converts a HTTP failure into an R error with the status line attached, which is far easier to diagnose than a NULL that propagates three functions downstream. Keeping the token in an environment variable rather than in the script keeps credentials out of version control. And the stopifnot() schema check at the end is the cheapest possible test that the vendor has not renamed a field.

Rate limits deserve their own line of defence: on a 429 response, sleep for the interval the API advertises and retry once or twice before failing. That is five lines of code and it removes an entire category of nightly-job failures.

Parsing XML and HTML documents

XML is a tree, so the reader must give you a tree plus a query language rather than a flat table. xml2 supplies XPath, and the usual workflow is to locate nodes once and then extract text or attributes.

library(xml2)
library(dplyr)
library(rvest)

doc <- read_xml("data/catalogue.xml")

# Every <product> node, then its children as columns
nodes <- xml_find_all(doc, "//product")
products <- tibble(
  sku      = xml_attr(nodes, "sku"),
  name     = xml_text(xml_find_first(nodes, "name")),
  price    = as.numeric(xml_text(xml_find_first(nodes, "price"))),
  in_stock = xml_text(xml_find_first(nodes, "stock")) == "yes"
)

# HTML pages behave the same way with CSS selectors
page <- read_html("https://example.com/pricing")
tiers <- page |>
  html_elements(".pricing-table .tier") |>
  lapply(function(node) {
    tibble(
      tier = html_text2(html_element(node, "h3")),
      usd  = as.numeric(gsub("[^0-9.]", "", html_text2(html_element(node, ".price"))))
    )
  }) |>
  bind_rows()

Three details cause most of the pain. Namespaces make XPath silently match nothing — declare them with xml_ns() or strip them from the document. Text nodes carry whitespace, so html_text2() (which collapses runs of spaces) beats raw xml_text() for scraped pages. And prices scraped out of text arrive as character with currency symbols attached, which means the numeric conversion belongs in a small helper you test once rather than inline in a loop.

Reading files larger than memory

A 12 GB extract does not fit in a laptop's RAM, but it does fit on disk, and most of the work you want to do can be expressed as a per-chunk transformation. Two strategies cover nearly every case: stream with a callback that keeps only what it needs, or use a reader that parses in C with minimal copying.

library(readr)
library(dplyr)

# Stream the file, keeping only rows that matter
totals <- read_csv_chunked(
  "data/telemetry.csv",
  callback = DataFrameCallback$new(function(chunk, pos) {
    tibble(
      window = floor(pos / 1e6),
      high_temp = sum(chunk$temp_c > 40, na.rm = TRUE),
      rows = nrow(chunk)
    )
  }),
  chunk_size = 1e6,
  col_types = cols(device = col_character(), temp_c = col_double())
)

# Or parse the whole file in one fast pass
library(data.table)
raw <- fread("data/telemetry.csv", showProgress = FALSE)
summary_stats <- raw[, .(mean_temp = mean(temp_c, na.rm = TRUE),
                         p99 = quantile(temp_c, 0.99, na.rm = TRUE)),
                     by = device]

# Columnar storage for files you re-read in every session
library(fst)
write_fst(as.data.frame(raw), "data/telemetry.fst")
reloaded <- read_fst("data/telemetry.fst")

Chunked reading is the right tool when you need a subset or a running aggregate, because I/O dominates and you never materialise the full table. fread() is the right tool when you need the whole table, since it auto-detects the delimiter and runs entirely in compiled code. fst collapses re-reads from minutes to seconds for data frames you touch repeatedly, at the cost of a format only R understands.

Databases: push the filter down

The single most effective performance decision in a database import is to let the database do the filtering, joining, and aggregation, then pull only the small result across the wire. The second most effective is to write the result somewhere durable instead of re-querying on every run.

library(DBI)
library(dplyr)
library(lubridate)

con <- dbConnect(RPostgres::Postgres(),
  dbname = "analytics", host = "db.internal", port = 5432,
  user = Sys.getenv("DB_USER"), password = Sys.getenv("DB_PASS")
)
on.exit(dbDisconnect(con), add = TRUE)

# The whole pipeline compiles to one SQL statement
revenue <- tbl(con, "orders") |>
  filter(order_date >= "2026-01-01", status == "paid") %>%
  mutate(month = floor_date(order_date, "month")) %>%
  group_by(month, region) %>%
  summarise(revenue = sum(amount), orders = n(), .groups = "drop") %>%
  collect()

# Parameterized query for values that come from input
region <- "EMEA"
dbGetQuery(
  con,
  "SELECT region, COUNT(*) AS n, SUM(amount) AS total
     FROM orders WHERE region = ? AND status = 'paid'
    GROUP BY region",
  params = list(region)
)

dbWriteTable(con, "revenue_monthly", revenue, overwrite = TRUE)

collect() is the boundary: before it you are building SQL, after it you are holding a data frame. Putting it last keeps work in the warehouse. Parameter placeholders prevent injection for any value that originates from a user or a config file, and on.exit() guarantees the connection closes even when the script fails halfway through.

Exporting for the next tool in the chain

Exports are contracts too. Whoever consumes the file — a colleague, a dashboard, a Python job, a vendor — needs predictable names, types, and missing-value markers, and needs to be able to re-read what you wrote without guessing.

ConsumerFormatEncodingMissing values
Excel users.xlsx via writexln/aempty cells
pandas / PythonCSVUTF-8empty string
Another R scriptRDSbinarynative NA
Warehouse loadCSV or ParquetUTF-8NULL / \N
European locale CSVCSVUTF-8decimal comma declared
library(readr)
library(writexl)

# UTF-8 CSV with declared missing marker: survives any consumer
write_csv(revenue, "output/revenue.csv", na = "NA", quote = "needed")

# Excel for humans, with one sheet per object
writexl::write_xlsx(
  list(Monthly = revenue, Region = aggregate(revenue ~ region, revenue, sum)),
  "output/revenue_report.xlsx"
)

# Binary for R: exact types, no parsing on the way back
saveRDS(revenue, "output/revenue.rds")

# Fixed-width for a mainframe partner that rejects CSV
write_fwf(revenue,
  file = "output/revenue.fwf",
  na = "",
  col_positions = fwf_widths(c(10, 10, 8, 14))
)

Set the encoding explicitly when the consumer is not R: write_csv() emits UTF-8 by default, but reading it back on a Windows machine with a legacy code page requires locale = locale(encoding = "UTF-8") on the other side. Agreeing on that once, in the export function, is cheaper than a support ticket about mojibake in a customer name.

Failures that only appear downstream

Common Mistakes

Pulling an entire table and filtering it in R

Fix: Filter, aggregate, and join inside SQL with dplyr's dbplyr backend, then collect the small result.

Parsing a JSON payload with string splitting or regular expressions

Fix: Use jsonlite::fromJSON() or httr::content(), which handle nesting, escapes, and unicode correctly.

Ignoring HTTP status codes and treating NULL as empty data

Fix: Call stop_for_status() and check for a zero-length payload explicitly so outages look like errors.

Reading a 20 GB file with read.csv() and hoping for the best

Fix: Stream with read_csv_chunked(), or parse with data.table::fread(), which uses a fraction of the memory.

Exporting without declaring encoding or missing-value markers

Fix: Write UTF-8, state na explicitly, and document the contract in one export function.

Embedding API tokens and database passwords in scripts

Fix: Read credentials from environment variables or a secret manager and never commit them.

Designing an import layer worth keeping

Best Practices

  • Give every source one reader function that returns typed columns plus read metadata.
  • Validate the schema at the boundary with stopifnot() or assertthat before any transformation runs.
  • Log source name, row count, column names, and problem count on every successful read.
  • Cache expensive API and database pulls on a schedule instead of re-fetching interactively.
  • Keep credentials in environment variables and reference them with Sys.getenv().
  • Write derived data once to a durable location so analyses do not repeat the fetch.
  • Test readers against a small fixture file so a vendor schema change fails your test suite first.

Key takeaways

Key Takeaways

  • Design imports around a contract — typed columns plus metadata — rather than around individual files.
  • Match the reader to size and frequency: readr for diagnostics, fread for scale, fst for repeat reads.
  • Web APIs need status checks, pagination limits, and schema assertions; the happy path is not the only path.
  • XML and HTML are trees, so XPath or CSS selectors plus careful text cleaning replace brittle string parsing.
  • Chunked reading processes files larger than memory without ever loading them whole.
  • Push filters into the database and collect last; pull only the result you actually need.
  • Exports are contracts too: declare encoding, missing values, and types for whoever reads next.

Where to go next

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement