Reading — step 1 of 4
Learn
R was designed to ingest, manipulate, and emit data. The IO functions are battle-tested.
read.csv / write.csv:
df <- read.csv("data.csv")
write.csv(df, "out.csv", row.names = FALSE)
Key args:
header = TRUE— first row is column names (default)stringsAsFactors = FALSE— don't auto-convert strings to factors (default in R 4.0+)na.strings = c("", "NA", "N/A")— values to treat as NAsep = ","— field separator (use\tfor TSV)colClasses = c("character", "numeric", "Date")— explicit types
read.table is the parent — more flexible:
df <- read.table("data.tsv", header = TRUE, sep = "\t")
readr package (tidyverse) is faster and infers types better:
library(readr)
df <- read_csv("data.csv") # tibble, no factors
write_csv(df, "out.csv")
readLines for raw text:
lines <- readLines("file.txt", warn = FALSE)
for (line in lines) cat(toupper(line), "\n")
Use "stdin" to read from standard input — that's what we've been doing.
scan for fast numeric reading:
nums <- scan("file.txt", what = numeric())
Much faster than read.csv for plain numeric data.
JSON with jsonlite:
library(jsonlite)
data <- fromJSON("data.json")
writeJSON(data, "out.json", pretty = TRUE)
Handles nested structures, simplifies arrays-of-objects to data frames.
Excel with readxl:
library(readxl)
df <- read_excel("file.xlsx", sheet = 1)
Database with DBI + driver package (RSQLite, RPostgres, etc.):
library(DBI)
con <- dbConnect(RSQLite::SQLite(), "db.sqlite")
df <- dbGetQuery(con, "SELECT * FROM users WHERE active = 1")
dbDisconnect(con)
The DBI interface is consistent across drivers — switch from SQLite to PostgreSQL just by changing the driver.
Practical patterns:
- Always check
nrow(df)andsummary(df)after reading head(df)andstr(df)show structure quickly- For huge files:
data.table::freadis dramatically faster thanread.csv - For streaming: read in chunks with
nrowsargument or usereadr::read_csv_chunked
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…