R data I/O
last modified November 19, 2026
Data rarely stays inside one R session. A table arrives as a CSV file, a model
is saved for later use, and a report is exported as text. R reads and writes
files relative to the working directory, which getwd reports and
setwd changes. This article covers CSV files, general delimited
text with read.table, the RDS format for arbitrary R objects,
plain text lines, the low-level scan function, and the handling
of missing values during import.
Writing and reading CSV
write.csv writes a data frame as comma-separated text with a
header row. read.csv reads it back and returns a data frame.
The row.names argument controls whether the row names become an
extra column; setting it to FALSE keeps the file limited to the
actual variables.
scores <- data.frame(name = c("Ada", "Grace", "Alan"),
score = c(91, 88, 84))
write.csv(scores, "scores.csv", row.names = FALSE)
back <- read.csv("scores.csv")
print(back)
cat("columns:", ncol(back), "\n")
unlink("scores.csv")
The file holds a header and three rows, and the read-back frame has the same
two columns as the original. Character columns stay character and numeric
columns stay numeric, because read.csv no longer converts strings
to factors by default. The row numbers printed on the left are row names that
R generated during the import; they are not stored in the file. The script
removes the file with unlink after the check.
$ Rscript csv.R name score 1 Ada 91 2 Grace 88 3 Alan 84 columns: 2
Delimited text tables
read.table is the general reader behind read.csv.
It accepts a separator, a header flag, and column classes as arguments, so it
handles semicolons, tabs, and pipes. A semicolon-separated file is common in
locales where the comma is the decimal mark.
lines <- "id;city;temp
1;Bratislava;12.5
2;Kosice;10.0
3;Zilina;8.5"
writeLines(lines, "weather.txt")
weather <- read.table("weather.txt", header = TRUE, sep = ";")
print(weather)
str(weather)
unlink("weather.txt")
The three rows are parsed into an integer column, a character column, and a
numeric column, as str reports. The header names become the
column names, and the values line up under them. Reading the same file with
the default separator would produce a single character column, because the
default splits on whitespace rather than on the semicolon. The separator
argument must match the file exactly.
$ Rscript delimited.R id city temp 1 1 Bratislava 12.5 2 2 Kosice 10.0 3 3 Zilina 8.5 'data.frame': 3 obs. of 3 variables: $ id : int 1 2 3 $ city: chr "Bratislava" "Kosice" "Zilina" $ temp: num 12.5 10 8.5
Saving R objects with RDS
A CSV file stores a table as text, so it cannot hold a model, a list, or a
function. The RDS format serialises any single R object and restores it
exactly. saveRDS writes the file and readRDS returns
the object, without the name that save would attach to it.
model <- lm(mpg ~ wt, data = mtcars)
saveRDS(model, "model.rds")
cat("bytes:", file.size("model.rds"), "\n")
restored <- readRDS("model.rds")
print(round(coef(restored), 3))
cat("identical:", identical(coef(model), coef(restored)), "\n")
unlink("model.rds")
The fitted model is stored in 2390 bytes and restored with identical
coefficients, 37.285 for the intercept and -5.344 for the slope. The
identical check is stricter than comparing the printed values,
because it compares the floating-point numbers themselves. An RDS file is
readable only by R, which is the price of preserving every attribute and
class. Use save and load when several objects should
travel together.
$ Rscript rds.R
bytes: 2390
(Intercept) wt
37.285 -5.344
identical: TRUE
Reading and writing lines
Not every file is a table. Logs, notes, and configuration files are sequences
of lines, and readLines returns them as a character vector.
writeLines performs the reverse operation and terminates every
line with a newline character.
writeLines(c("first line", "second line", "third line"), "notes.txt")
lines <- readLines("notes.txt")
cat("lines:", length(lines), "\n")
print(lines)
print(nchar(lines))
unlink("notes.txt")
The file contains three lines, and readLines returns them without
the trailing newline characters. Their lengths are 10, 11, and 10 characters,
which counts the letters and the spaces but not the line endings. A file
without a final newline still reads correctly, although many tools expect the
last line to end with one. The warn argument of
readLines reports missing line endings when it is set to
TRUE.
$ Rscript text-lines.R lines: 3 [1] "first line" "second line" "third line" [1] 10 11 10
Scanning numbers
scan is the lowest-level text reader in R. It reads whitespace-
separated tokens and converts them to a requested type. The text
argument reads from a string instead of a file, which makes the function easy
to demonstrate without creating one.
text <- "3.5 4.1 2.8 5.0"
values <- scan(text = text, quiet = TRUE)
print(values)
cat("mean:", mean(values), "\n")
print(scan(text = "10 20 30", what = integer(), quiet = TRUE))
The four numbers are parsed as doubles by default, and their mean is 3.85.
The second call sets what = integer(), so the result is an
integer vector of three values. quiet = TRUE suppresses the
message that reports how many items were read. read.table uses
scan internally, which is why the two functions share the same
rules for whitespace and comments.
$ Rscript scan-numbers.R [1] 3.5 4.1 2.8 5.0 mean: 3.85 [1] 10 20 30
Missing values during import
Text files have no native missing value, so they use a sentinel such as an
empty field, NA, or a word like missing. The
na.strings argument maps those strings to NA while
the file is being read, which keeps the column numeric instead of turning it
into text.
lines <- "x,y
1,2
3,missing
5,6"
writeLines(lines, "pairs.csv")
pairs <- read.csv("pairs.csv", na.strings = "missing")
print(pairs)
cat("complete rows:", sum(complete.cases(pairs)), "\n")
print(colSums(is.na(pairs)))
unlink("pairs.csv")
The sentinel is recognised and the y column holds two numbers and
one missing value. Only two rows are complete, and colSums over
is.na shows that the missing value sits in y, not in
x. Without na.strings, the whole column would be
read as character, and later arithmetic would fail or coerce the numbers in
unexpected ways.
$ Rscript import-missing.R x y 1 1 2 2 3 NA 3 5 6 complete rows: 2 x y 0 1
A complete example
The final script exports one small table twice. The CSV version writes missing
values as empty fields and reads them back with
na.strings = "". The RDS version keeps the data frame exactly as
it was, including the missing value and the column types.
df <- data.frame(id = 1:4, city = c("BA", "KE", "ZA", "PO"),
value = c(12.5, 10, NA, 8.5))
write.csv(df, "report.csv", row.names = FALSE, na = "")
saveRDS(df, "report.rds")
from_csv <- read.csv("report.csv", na.strings = "")
from_rds <- readRDS("report.rds")
print(from_csv)
cat("csv columns:", ncol(from_csv), "\n")
cat("rds identical:", identical(df, from_rds), "\n")
cat("na rows in csv:", sum(is.na(from_csv$value)), "\n")
unlink(c("report.csv", "report.rds"))
Both files restore the same four rows and three columns, and the RDS copy is identical to the original. The CSV copy is equal in content but not necessarily in type: a date column would arrive as text, and a factor would arrive as a character vector unless it is converted again. CSV is the right format for exchange with other programs, and RDS is the right format for keeping an R object between sessions.
$ Rscript report.R id city value 1 1 BA 12.5 2 2 KE 10.0 3 3 ZA NA 4 4 PO 8.5 csv columns: 3 rds identical: TRUE na rows in csv: 1
Next steps
The data frames article explains the structure
that read.csv returns, and the
tibbles article shows the tidyverse variant that
prints more compactly. The missing values
article covers NA, complete.cases, and the
na.rm argument in more detail. The
packages article explains how to install the
readers for formats that base R does not support; the
Excel article covers .xlsx workbooks,
and the JSON article covers JSON.
Source
R documentation: readRDS and saveRDS
In this article we have written and read CSV files and general delimited
tables, and checked the column types after import. We saved a fitted model in
RDS format and verified that it came back unchanged, then read and wrote plain
text lines. We parsed numbers from a string with scan and mapped
a sentinel to NA during import. The final example exported the
same table in both formats and compared what each one preserved. The next
articles turn to customising ggplot2 graphics and to the S3 object system.
Author
List all R Language tutorials.