Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
write.table() in R exports a data frame or matrix as delimited text. Set the separator, row-name handling and missing-value marker explicitly, then read the file back with matching settings. The worked example below checks leading-zero identifiers, missing measurements and embedded quotes, so a successful write is followed by a check of the actual data.
What it is used for in research
Use write.table() when an analysis needs to produce a rectangular text table for another program or collaborator. It accepts a matrix or data frame, and attempts to convert other input to a data frame. The destination can be a named file or a writable connection. The R Core Team’s Data Output reference documents these behaviors.
A data frame can contain columns of different types, such as character identifiers and numeric measurements. That makes it a useful starting point for the example here. If the object itself is unfamiliar, see data frames in R programming. Exporting that object as text requires decisions about how its values should appear outside R.
Keep the deliverable clear: this function writes a text representation of a table. Changing the filename to end in .xlsx does not create an Excel workbook. For sheets and workbook output, use the separate workflow for writing XLSX files in R. The task here is a configurable delimited export with a documented reading recipe.
Install or access
write.table() is documented in R’s utils package. Use utils::write.table() to name it explicitly; no additional export package is needed for this tutorial. The R Project provides the official download route through CRAN and describes R as free software for statistical computing and graphics.
Start an R session and choose a writable working directory. getwd() reports the current directory, as described in the working-directory reference. The relative filename used below is resolved in that directory. Use a fresh output name: the default append = FALSE replaces an existing file at the destination.
getwd()
help("write.table", package = "utils")
Run the commands in an R console or script. Keep the export call with the analysis code so the separator and missing-value choices are visible when the file is regenerated. Those choices also belong in the instructions given to whoever imports the table.
Step-by-step task: write.table in R
write.table R syntax and the important defaults
The short form is write.table(x, file), but several defaults deserve attention. The default separator is a space, not a tab or comma; row names and column names are written; missing values use NA; and existing files are replaced. The example deliberately overrides the separator and row-name setting.
quote = TRUE quotes ordinary character and factor columns, plus written row and column names. It does not mean that every numeric value receives quotes. qmethod controls embedded double quotes inside quoted strings: the default uses backslash escaping, while qmethod = "double" doubles them. Choose a convention the receiving reader supports.
- Create an example table. These are synthetic values in an illustrative composite, not observations from a study. The identifiers are character strings, the second measurement is missing, and the notes deliberately include punctuation and a quote.
results <- data.frame(
sample_id = c("001", "002", "003"),
score = c(12.5, NA, 8.25),
note = c("baseline", "repeat, check", 'review "flag"'),
stringsAsFactors = FALSE
)
The data.frame reference explains how named arguments create columns. Here, sample_id is an ordinary column rather than a row label. That makes the identifier’s role explicit when the table moves between programs.
- Write a tab-separated file. Keep the column header, omit automatic row names, use
NAfor missing values and request UTF-8 for the named file. The quote convention is chosen to match the read-back step.
utils::write.table(
results,
file = "results.tsv",
sep = "\t",
row.names = FALSE,
col.names = TRUE,
quote = TRUE,
qmethod = "double",
na = "NA",
dec = ".",
fileEncoding = "UTF-8"
)
"\t" is R’s tab escape within a string. The call writes tab characters between fields. The .tsv suffix communicates that choice to a reader, but the function follows sep, not the suffix. UTF-8 is an explicit encoding choice for this example; the receiving program must use a compatible interpretation.
- Inspect the actual text.
readLines()reads lines from the file, andcat()displays them without the extra printed-string representation that can obscure quotation marks.
cat(readLines("results.tsv", n = 4), sep = "\n")
The output is shown below with tabs between fields. The doubled quotes around flag are part of the file’s escaping convention; they are not two quote characters in the original note.
"sample_id" "score" "note"
"001" 12.5 "baseline"
"002" NA "repeat, check"
"003" 8.25 "review ""flag"""
- Read the table back with explicit types. Match the delimiter, decimal mark, missing-value marker and encoding. Declare the identifier column as character so
001is not interpreted as the number1.
restored <- read.table(
"results.tsv",
header = TRUE,
sep = "\t",
quote = "\"",
dec = ".",
na.strings = "NA",
colClasses = c("character", "numeric", "character"),
comment.char = "",
check.names = FALSE,
fileEncoding = "UTF-8"
)
stopifnot(
identical(names(restored), names(results)),
identical(restored$sample_id, results$sample_id),
identical(restored$score, results$score),
identical(restored$note, results$note)
)
The Data Input reference documents colClasses, na.strings and the other reader settings. If an assertion fails, inspect the relevant column before distributing the file. Passing these checks confirms the example’s names and column values; it is not a blanket guarantee that every possible R attribute survives text export.
Output and how to read it
The intended file has one header line, three data records and three fields per record. There is no extra column containing R’s automatic row numbers. The comma in repeat, check remains part of a note because the separator is a tab. The missing score is represented by the unquoted marker NA.
The reader reconstructs those text fields as R columns. Without an explicit character class, numeric-looking identifiers may be converted to numbers. Quoting an identifier in the export is not a substitute for specifying its input type. The deliberate leading zeros in this example make that problem visible during verification.
The downloadable data table below pairs writer settings with the corresponding reader settings. It joins the separate Data Output and Data Input references into a handover checklist. For the broader import workflow, including choosing readers for other file types, see read.table in R.
Write table in R with another separator
For a receiving program that expects semicolon-separated fields and decimal commas, change both sep and dec. A delimiter and a decimal mark perform different jobs. Here is an illustrative export using the same table:
write.table(
results, "results-semicolon.txt",
sep = ";", dec = ",",
row.names = FALSE,
quote = TRUE, qmethod = "double",
fileEncoding = "UTF-8"
)
Its reader must use sep = ";" and dec = ",", along with the character identifier type. For a standard CSV task, the convenience wrappers reduce these choices; see writing CSV files in R. Call write.table() directly when you need to control conventions that those wrappers fix.
Troubleshooting
An unwanted first column or a shifted header
Check row.names first. Its default is TRUE, so automatic row numbers can become an extra exported field. Use row.names = FALSE when identifiers already occupy an ordinary column, as they do in the example.
If meaningful identifiers really are stored as row names, preserve them deliberately. With row.names = TRUE, col.names = NA adds an empty header for that field. A corresponding read.table() call can use row.names = 1. Do not combine that reader setting with the example’s row-name-free export: it would consume the sample identifier column as row labels.
The receiving program splits or changes text
Compare the actual delimiter and quote convention with the import settings. Turning off quoting is not a general fix for parsing problems. Text containing a delimiter or embedded quote needs an agreed representation; inspect those fields in the receiving tool as well as in the raw file. The R Data Import/Export manual illustrates the difference between backslash escaping and doubled quotes.
Also coordinate missing values. The writer’s na and the reader’s na.strings should agree. A literal data value that matches the selected missing-value marker creates ambiguity, so choose and document a marker appropriate to the table. Empty strings and missing measurements should not be treated as interchangeable merely because both look blank in a spreadsheet.
Appending repeats the header or adds mismatched columns
append = TRUE adds output to a named file. Suppress the second header yourself with col.names = FALSE. Before appending, ensure the new rows have the same column order and use the same export conventions. This example adds one synthetic record to the file created above:
next_batch <- data.frame(
sample_id = "004", score = 9.5, note = "follow-up",
stringsAsFactors = FALSE
)
stopifnot(identical(names(next_batch), names(results)))
write.table(
next_batch, "results.tsv",
append = TRUE, col.names = FALSE,
sep = "\t", row.names = FALSE,
quote = TRUE, qmethod = "double",
na = "NA", dec = ".", fileEncoding = "UTF-8"
)
Run this append step once to add one record. Repeating it adds the record again: appending is not a key-based update. Re-read the combined file to check it. The column-name assertion checks order and names, not whether every new value meets the research project’s validation rules.
Characters, precision or object structure change
Match the encoding at import and export, especially for names and labels containing non-ASCII characters. The manual notes that text tables do not carry encoding metadata. fileEncoding on write.table() applies to a named file; a connection needs its encoding configured through the connection instead.
Do not assume console rounding determines the written numeric precision. The export documentation distinguishes numeric conversion from displayed formatting. Use a deliberate formatting step when fixed presentation is required, recognizing that formatting numbers as strings changes what is handed to the reader. For analysis exchange, verify the imported numeric values rather than judging aligned decimal places.
Finally, inspect complex columns before treating the file as a faithful copy of an R object. Matrix-like columns can expand into multiple output columns, while list or classed columns can be converted through character methods. For preserving a single R object rather than exchanging a flat table, consider the R serialization alternative below.
Free alternatives
These functions are available within R; the table compares their documented output roles rather than prices or performance. Their different file conventions matter more than a similar function name.
| Function | Output role | Documented distinction | Official source |
|---|---|---|---|
write.csv() |
Comma-separated text | Uses a period decimal mark and doubled quotes; several format arguments are fixed. | R Data Output |
write.csv2() |
Semicolon-separated text | Uses a comma decimal mark and doubled quotes; several format arguments are fixed. | R Data Output |
saveRDS() |
Serialization of one R object | Restore with readRDS(); the documentation warns against using RDS as a general interchange format between machines. |
R Serialization Interface for Single Objects |
Choose an output according to the recipient’s actual reader. write.csv() and write.csv2() ignore attempts to alter append, col.names, sep, dec or qmethod, with a warning. A custom separator or the controlled append workflow therefore calls for write.table() itself. Serialization solves a different task from delivering a delimited research table.
Sources
- R Core Team, Data Output: write.table, write.csv and write.csv2. Checked 2026-11-16.
- R Core Team, Data Input: read.table and related readers. Checked 2026-11-16.
- R Core Team, R Data Import/Export, section 1.2: Export to text files. Checked 2026-11-16.
- R Core Team, Data Frames. Checked 2026-11-16.
- R Core Team, Get or Set Working Directory. Checked 2026-11-16.
- R Core Team, Read Text Lines from a Connection. Checked 2026-11-16.
- R Core Team, Serialization Interface for Single Objects. Checked 2026-11-16.
- R Project, The R Project for Statistical Computing. Checked 2026-11-16.
Data: write.table export settings paired with R reader settings
An original crosswalk compiled from the R Data Output and Data Input references. It pairs export conventions with explicit reader settings and identifies the interpretation each pair controls; it is not a table of measured research observations.
| Convention | Writer setting | Reader setting | Interpretation | Sources |
|---|---|---|---|---|
| Tab delimiter | sep = "\t" | sep = "\t" | Use the same tab separator when writing and reading. | Data Output; Data Input |
| Column header | col.names = TRUE | header = TRUE | Write variable names once and interpret the first line as the header. | Data Output; Data Input |
| No exported row labels | row.names = FALSE | Omit row.names = 1 | Keep ordinary identifier columns as data rather than consuming one as row names. | Data Output; Data Input |
| Missing marker | na = "NA" | na.strings = "NA" | Coordinate the marker written for missing values with the marker recognized on input. | Data Output; Data Input |
| Decimal comma with semicolon fields | sep = ";", dec = "," | sep = ";", dec = "," | Declare field separation and numeric decimal interpretation separately. | Data Output; Data Input |
| Character identifiers | Keep the source identifier column character | colClasses = "character" for that column | Prevent numeric-looking identifiers from being converted to numeric values during input. | Data Output; Data Input |
| Named-file encoding | fileEncoding = "UTF-8" | fileEncoding = "UTF-8" | Use a matching declared encoding for this named-file workflow. | Data Output; Data Input |
Sources
- R Core Team: Data Output (write.table) (accessed 2026-11-16)
- R Core Team: Data Input (read.table) (accessed 2026-11-16)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







