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

Reading and Writing Files in R: CSV, Excel, and Databases

R BasicsFile HandlingđŸŸĸ Free Lesson

Reading and Writing Files in R

R Basics

The contract between your script and your data

Every analysis begins with a hand-off: bytes sitting on a disk, a database, or an API have to become an R object without losing or inventing anything in the process. Most data science bugs in R are not statistical, they are I/O bugs — a column silently read as text, a decimal comma swallowed, a row of headers shifted one column to the left, a UTF-8 file decoded as Latin-1 so that names come back with odd marks. Reading a file is not a formality you do before the real work; it is the step where you decide what your data means.

  • Decide the column types before you trust any summary.
  • Treat encoding, separators, and missing-value markers as explicit decisions.
  • Write files that another person, in another session, can re-read byte for byte.

Prerequisites

  • !R vectors and data frames
  • !Working with directories and paths

What You'll Learn

  • 1Choose the correct reader for delimited, Excel, JSON, and database sources
  • 2Control column types, missing values, and encodings while importing
  • 3Export files that round-trip cleanly without stray row names or quoted numerics
  • 4Build scripts that run unchanged on another machine

What actually happens when R reads a file

A reader performs three jobs in sequence. First it slices the raw text into fields using a separator, a quote character, and a comment marker. Second it guesses a type for each column from the strings it saw — a column that contains only digits becomes numeric, a column containing "NA" or "T" partway down may become character. Third it converts each field into an R value, marking anything unparseable as NA and usually continuing without complaint.

That third step is where data disappears quietly. Base R's read.csv() will happily turn a five-digit zip code into a number, drop a column's leading zeros, or convert a column of dates into character because three rows contain the text "unknown". The reader is doing exactly what you asked; you simply never asked anything specific. The fix is to make every one of those three decisions explicit — separator, type, and missing-value marker — so that the object you receive is the object you meant to receive.

There is also a cost dimension. Base R's readers are written in C and are fast enough for files up to a few hundred megabytes, but readr and data.table::fread() parse noticeably faster on multi-gigabyte inputs and report problems in a structured way instead of warning you once and moving on. Choosing a reader is therefore a choice about diagnostics as much as speed.

Matching the reader to the format

Different sources deserve different tools, and the ecosystem gives you a tidy option and a base option for almost everything. The table below is the decision I actually use when starting a project.

FormatRecommended readerBase R fallbackWatch out for
CSV / TSVreadr::read_csv()read.csv()delimiter sniffing, decimal commas
Fixed-width textreadr::read_fwf()read.fwf()column positions shift when rows wrap
Excel (.xlsx)readxl::read_excel()nonemerged cells, dates stored as serial numbers
JSONjsonlite::fromJSON()nonenested records flatten into list-columns
R native objectreadRDS()readRDS()version compatibility across R releases
SQL tablesDBI::dbGetQuery()noneidentifier quoting differs per driver

Two conventions matter more than they look. Never write CSV with row names, because the extra unnamed column breaks re-import in most other tools, including pandas. And never rely on type guessing for a file you will read repeatedly: if the twelfth row of a numeric column is empty in one delivery and contains a stray space in the next, the inferred type changes and every downstream summary changes with it.

Delimited text: the options that matter

read_csv() exposes the decisions described above as arguments, and setting them once is usually cheaper than debugging later. Notice col_types, which pins every column, and locale, which handles encodings and decimal marks.

library(readr)

orders <- read_csv(
  "data/orders.csv",
  col_types = cols(
    order_id   = col_integer(),
    ordered_at = col_date(format = "%Y-%m-%d"),
    country    = col_character(),
    amount     = col_double(),
    discount   = col_number()
  ),
  na = c("", "NA", "N/A", "-"),
  trim_ws = TRUE,
  locale = locale(decimal_mark = ".", grouping_mark = ",")
)

# If anything fails to parse, inspect it rather than ignore it
problems(orders)

# A damaged file rarely fails loudly — count rows before and after
nrow(orders)
count(fields = "data/orders.csv") |> print(n = 5)

The problems() call deserves emphasis. It returns a data frame of every cell that could not be converted, with row, column, expected type, and the offending string. A pipeline that never calls it is a pipeline that converts bad cells to NA and reports a slightly smaller mean, which is far harder to notice than an error.

When the separator is unknown — common with exports from legacy systems — read_delim() with an explicit delim beats guessing, and read_tsv() avoids the issue entirely for tab-separated files. For files with a preamble of junk lines, skip moves the start; for files without a header, col_names = FALSE followed by names<- keeps column positions stable across runs.

Writing files other people can open

Exporting has its own failure modes. The most common is the extra column of row names that write.csv() adds by default, which shows up in Excel as an unlabeled first column and breaks re-import. The second is numeric formatting: R writes fifteen significant digits by default, so an identifier like 001234567890 arrives in another tool as scientific notation.

library(readr)

# Clean export: no row names, explicit NA handling, stable quoting
write_csv(orders, "output/orders_clean.csv", na = "", quote = "needed")

# Round numbers only at the point of export, never in the data frame
financials <- transform(gross, amount = round(amount, 2))
write_csv(financials, "output/finances.csv", na = "")

# Tab-separated survives Excel's CSV importer better with European locales
write_tsv(orders, "output/orders.tsv", na = "")

# Preserve exact types for another R session instead of a text file
saveRDS(orders, "output/orders.rds")
orders_again <- readRDS("output/orders.rds")

Use CSV for interchange with people and other languages, and RDS for handing objects between your own scripts. RDS round-trips factors, dates, list-columns, and column types exactly, but it is unreadable outside R, so a file meant for a colleague in Excel or pandas must be CSV or Excel. Keeping both — a canonical RDS and a exported CSV — is a cheap habit that removes an entire class of "which version is right" conversations.

Excel without the guesswork

Excel files are structurally messier than CSV because a worksheet is a grid, not a table: title rows, merged headers, footnotes, and two data blocks stacked vertically. readxl reads what is in the cells, including empty ones, so the arguments you use most are skip, range, col_names, and sheet.

library(readxl)
library(writexl)

excel_sheets("reports/q3.xlsx")            # inspect before reading

q3 <- read_excel(
  "reports/q3.xlsx",
  sheet = "Q3 Detail",
  range = "A4:H200",
  col_names = c("region", "rep", "quarter", "units",
                "revenue", "cost", "margin", "notes"),
  col_types = c("text", "text", "date", "numeric",
                "numeric", "numeric", "numeric", "text"),
  na = c("n/a", "-", "")
)

# Write one workbook with several sheets; names become sheet names
writexl::write_xlsx(
  list(Quarter = q3, Summary = aggregate(revenue ~ region, q3, sum)),
  "output/q3_report.xlsx"
)

Two Excel quirks cost time repeatedly. Dates arrive as serial numbers when a column's format is inconsistent, so col_types = "date" forces the conversion and readxl handles the 1900 versus 1904 epoch for you. And a "number" stored as text right-aligns in Excel but imports as character, producing a column of NA after a failed numeric conversion — problems() catches this immediately.

Paths that survive a new machine

Hard-coded absolute paths are the single biggest reason a script works on your laptop and fails in CI. Build paths with file.path(), which inserts the correct separator on Windows and Unix alike, and resolve project-relative locations with here::here() if the project uses it.

# Construct rather than concatenate
raw_dir  <- file.path("data", "raw")
out_dir  <- file.path("data", "derived")
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)

files <- list.files(raw_dir, pattern = "\\.csv$", full.names = TRUE)

# Read a directory of files, keeping the source name as a column
library(purrr)
library(dplyr)

one_file <- function(path) {
  read_csv(path, show_col_types = FALSE) |>
    mutate(source = basename(path), .before = 1)
}

inventory <- map_dfr(files, one_file)

# Guard the steps that can fail
stopifnot(file.exists(file.path(raw_dir, "inventory.csv")))
file.size(file.path(raw_dir, "inventory.csv"))

list.files() with a regular-expression pattern and full.names = TRUE is the backbone of batch workflows: one function, one directory, one bound data frame. Adding the source column before binding preserves provenance, so a suspicious row can be traced back to the file it came from instead of becoming an argument.

When the data lives in a database

Databases are files that answer queries. The DBI package defines one interface and drivers implement it, so the same code works against SQLite, PostgreSQL, and MySQL with only the connection call changed. Parameterized queries keep user input out of the SQL text, and always disconnecting keeps file locks and connection pools healthy.

library(DBI)

con <- dbConnect(RSQLite::SQLite(), "warehouse.sqlite")
on.exit(dbDisconnect(con), add = TRUE)

dbListTables(con)

# Everything user-supplied goes through a placeholder, never paste()
min_units <- 40
stock <- dbGetQuery(
  con,
  "SELECT sku, name, units FROM products WHERE units >= ? ORDER BY units DESC",
  params = list(min_units)
)

# Push the whole frame back in one statement
dbWriteTable(con, "stock_snapshot", stock, overwrite = TRUE)

# Lazy tbl() keeps the query in SQL until you collect()
library(dplyr)
tbl(con, "stock_snapshot") |>
  filter(units > 50) |>
  collect()

Two habits pay off here. on.exit() guarantees the connection closes even if the script errors halfway through, which matters for SQLite because a lingering handle can hold a write lock. And collect() should be the last step of a pipeline, not the first: filtering and aggregating inside the database moves the work to where the data already is, and only the small result set crosses the network.

Silent corruption and other traps

Common Mistakes

Trusting inferred column types on a file you will re-read every week

Fix: Pass an explicit col_types specification so a stray value can never change a column from double to character.

Letting write.csv() add a column of row names

Fix: Always pass row.names = FALSE, or use readr::write_csv() which never writes them.

Ignoring problems() after an import

Fix: Read it every time; each row it returns is a cell that became NA and will bias your summary.

Hard-coding C:/Users/yourname/data in scripts

Fix: Build paths with file.path() and keep data directories relative to the project root.

Opening a database connection without closing it

Fix: Register dbDisconnect() with on.exit() immediately after connecting.

Exporting fifteen significant digits for an identifier

Fix: Format identifiers as character before writing, and round measures only at export time.

Habits that make I/O boring

Best Practices

  • Pin column types on every import and record the specification next to the raw file.
  • Call problems() after each read and fail the pipeline when unexpected parse failures appear.
  • Keep raw data read-only; write all derived files into a separate derived directory.
  • Prefer CSV or TSV for interchange and RDS for objects that must round-trip exactly.
  • Wrap repeated read-clean-write logic in a single function with a path argument.
  • Log file size, row count, and column names at import so drift shows up in output, not in results.

Key takeaways

Key Takeaways

  • Reading a file is three decisions — delimiter, type, and missing-value marker — and making them explicit prevents almost all silent data loss.
  • readr gives you structured diagnostics through problems(); base readers mostly guess and continue.
  • Never write CSV with row names, and format identifiers as text before exporting.
  • Excel needs skip, range, and col_types because worksheets are grids rather than tables.
  • file.path() and here() keep scripts portable across operating systems and machines.
  • DBI's interface plus parameterized queries covers SQLite, PostgreSQL, and MySQL with one code pattern.
  • Round-trip your own objects with readRDS() and saveRDS() to preserve types exactly.

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