Data Import and Export

Article · 2:00

Flat files with readr, spreadsheets with readxl, and talking to a SQL database without writing SQL by hand.

Getting the data in is the step that eats the most time and gets the least attention, and almost every downstream problem starts here with a column that came in as the wrong type.

Flat files. Base R has read.csv(); readr::read_csv() is better and is what to use. It is several times faster, never converts strings to factors, returns a tibble, and - the part that matters most - prints the column types it guessed, so a date that arrived as text is visible immediately rather than three steps later. It guesses from the first 1,000 rows, which is where its one failure mode lives: a column that is numeric for 1,000 rows and then contains "N/A" will be guessed as numeric and that row becomes NA with a warning. The fix is col_types, stating what you expect. In a pipeline that runs repeatedly, state the types always - a guess that changes when the data changes is a pipeline that breaks silently.

Excel. readxl::read_excel() reads .xls and .xlsx with no Java and no Perl, which its predecessors needed. Give it sheet and range rather than reading everything and subsetting afterwards. For writing Excel, readxl is read-only - use writexl::write_xlsx() for something simple, or openxlsx when you need formatting, formulas or multiple sheets.

Databases. DBI is the common interface and a driver package does the talking: RPostgres, RMariaDB, RSQLite, odbc. Connect, and then the good part: dbplyr lets you write dplyr against a database table, and translates it into SQL that runs on the server. The data never comes into R until you ask for it with collect(), so you can filter a hundred-million-row table down to a thousand rows without the other 99,999,000 crossing the network. show_query() prints the SQL it generated, which is both a debugging tool and a good way to learn SQL.

Never put a password in a script. Sys.getenv("DB_PASSWORD") reads it from the environment, and the keyring package stores it in the operating system's credential store.

library(readr)
library(readxl)
library(writexl)
library(DBI)
library(dplyr)
library(dbplyr)

# ---- CSV and friends -------------------------------------------------
sales <- read_csv("sales.csv")
# read_csv PRINTS what it guessed. Read that output - it is the cheapest
# data quality check you will ever get:
#
#   Rows: 10000 Columns: 5
#   -- Column specification --------------------------
#   chr  (2): region, product
#   dbl  (2): units, revenue
#   date (1): order_date

# In anything that runs more than once, say what you expect rather than
# letting it guess. A guess that changes when the data changes is a
# pipeline that breaks without telling you.
sales <- read_csv(
  "sales.csv",
  col_types = cols(
    order_date = col_date(format = "%Y-%m-%d"),
    region     = col_character(),
    product    = col_factor(),
    units      = col_integer(),
    revenue    = col_double()
  )
)

read_tsv("data.tsv")
read_delim("data.txt", delim = "|")

# Common arguments worth knowing:
read_csv("messy.csv",
         skip      = 2,              # junk rows above the header
         na        = c("", "NA", "N/A", "-", "NULL"),   # all of these
         col_names = c("a", "b"),    # when the file has no header
         n_max     = 1000)           # peek at a huge file first

write_csv(sales, "clean.csv")        # no row names, UTF-8, ISO dates

# ---- Excel -----------------------------------------------------------
excel_sheets("report.xlsx")          # what is in there, before reading

q1 <- read_excel("report.xlsx", sheet = "Q1")
q1 <- read_excel("report.xlsx", sheet = 1, range = "B3:F200")
# range skips the title rows and the merged-cell decoration that make
# spreadsheets painful. Better than reading it all and cleaning after.

write_xlsx(list(Q1 = q1, Summary = sales), "out.xlsx")   # two sheets

# ---- Databases -------------------------------------------------------
con <- dbConnect(
  RPostgres::Postgres(),
  host     = "db.example.com",
  dbname   = "analytics",
  user     = Sys.getenv("DB_USER"),        # never a literal password
  password = Sys.getenv("DB_PASSWORD")
)

dbListTables(con)

# Raw SQL when you want it:
dbGetQuery(con, "SELECT region, SUM(revenue) FROM sales GROUP BY region")

# Or dplyr, translated to SQL and run on the SERVER:
orders <- tbl(con, "orders")          # a reference. No data moved yet.

big <- orders |>
  filter(order_date >= "2026-01-01", status == "complete") |>
  group_by(region) |>
  summarise(total = sum(revenue, na.rm = TRUE))

show_query(big)    # the SQL dbplyr generated. Read it.

results <- collect(big)   # NOW the data crosses the network - and it is
                          # the summary, not the hundred million rows.

dbDisconnect(con)

# ---- R's own formats -------------------------------------------------
saveRDS(sales, "sales.rds")          # ONE object, keeps every type
sales <- readRDS("sales.rds")        # and you choose the name back

# save()/load() write several objects AND their names, which is how a
# load() silently overwrites something you were using. Prefer RDS.

Discussion

No questions on this topic yet. Sign in to ask the first one.