Skip to main content
v2026.11,986 entries · CC-BY 4.0

fread in R: Syntax, Arguments and Examples

How to use fread() from R’s data.table package: installation, arguments, a runnable example, reading the output and fixing common errors.

Written and maintained by CASRAI Editorial Board

Published

On this page

fread() is the file-reading function of the R package data.table. It reads a delimited text file, such as a CSV or tab-separated export, into a data.table, and it detects the separator, the header, the column types and the number of rows without being told. The package documentation describes it as similar to read.csv() and read.delim() but faster and more convenient, so one call, fread("file.csv"), is usually enough to load a regular rectangular file.

This guide covers what fread does for research data, how to install it, a step-by-step reading workflow with a worked example you can run without any file, how to read the result, and the errors researchers most often meet. It is written for analysts working in R who receive instrument exports, survey downloads, registry extracts or repository files and need to load them reproducibly. The argument table at the end of the page lists the options that matter most for research data, with the default value of each.

What fread is used for in research

Researchers use fread to load delimited files into R as the first step of an analysis script. The function is documented for regular delimited files, meaning files in which every row has the same number of columns. Typical sources are exports from laboratory instruments, electronic data capture systems, survey platforms, public-health registries and data repositories.

Three properties make it useful beyond speed. First, automatic detection: the separator is chosen from the characters comma, tab, space, pipe, semicolon and colon by finding the one that splits a sample of the file into the most lines with the same field count, and the header, column types and decimal mark are detected too. Second, type detection that matches research needs: integers larger than 231 are read as bit64::integer64 by default (relevant for long participant or sample identifiers), and IDate and POSIXct date-time types are detected and read directly. Third, control without a rewrite: arguments such as select, drop, colClasses, nrows and na.strings let you decide exactly what enters memory and how it is typed, which matters when a script has to behave the same way on every run.

fread reads a file; it does not clean it. If a column mixes codes and free text, or a spreadsheet export carries notes under the table, you still decide how those are handled, and the Troubleshooting section below shows the arguments that apply. Writing results back out is the job of the companion function fwrite(), covered in the guide to writing CSV files from R.

How to install or access fread

fread is not a separate download. It is one function in the data.table package, which is installed from CRAN, the Comprehensive R Archive Network, with the standard R command:

install.packages("data.table")
library(data.table)

The data.table project home page gives this same command as the installation route. Its current release on CRAN is version 1.18.6.1, published 2026-08-24, and the project states a dependency on R 3.5.0 (2018) or later. The project also describes a development version that is installed from the project’s own repository with install.packages("data.table", repos="https://rdatatable.gitlab.io/data.table"); for a published analysis, the CRAN release is the version you can cite and others can install.

Two optional pieces extend what fread can read. Compressed files with the .gz or .bz2 extension are read directly when the R.utils package is installed. The cmd argument runs a shell command on the file before reading, and on Windows the documentation says tools such as grep come from Rtools, Cygwin or WSL. Neither is needed for plain CSV files.

Whichever version you use, record it in your analysis script or session information, because defaults can change between releases. The reference page for the development documentation, which is the source for the defaults quoted here, is listed under Sources.

How to read a delimited file with fread step by step

The steps below move from a first look at the file to a typed, memory-conscious read. File names such as trial_data.csv and the column names participant_id, visit_date and result are illustrative placeholders, not real data.

  1. Load the package. Run library(data.table).
  2. Pass the file as a single string. DT = fread("trial_data.csv"). The first argument, input, is deferred to file when the string contains no newline, to text when it contains at least one newline, and to cmd when it has no newline, contains a space and is not a file name. Use exactly one of input, file, text or cmd. The file argument accepts a name, a path or a URL starting with http:// or file://.
  3. Do a dry run on a large file. fread("trial_data.csv", nrows=0) returns the column names and typed empty columns, which the documentation describes as a dry run of a large file. You do not need to estimate a row count, because fread does not require one.
  4. Inspect the detection report. Add verbose=TRUE to see how fread sampled the file, which separator it chose and which types it assigned. This is the quickest way to find out why a column came back as character.
  5. Keep only the columns you need. fread("trial_data.csv", select=c("participant_id","visit_date","result")), or the reverse with drop=. Both take names or column numbers, and the order you give in select sets the order of the result. Selecting early limits memory use on wide files.
  6. Fix types you must control. colClasses=c(participant_id="character") forces an identifier to be text. If a requested conversion would cause an error, introduce NAs or lose accuracy, fread aborts it for that column and issues a warning, so check warnings after the read.
  7. Set the missing-value rule explicitly. Decide what the file means by an empty field, then set na.strings accordingly (see Troubleshooting).
  8. Run the script from a clean session and write the cleaned table with fwrite() if other people need the processed file, so the whole path from raw export to analysis table is repeatable.

A worked example you can run without a file

The text argument reads a string as if it were a file, which makes it possible to test behaviour before pointing fread at real data. This illustrative example is built from the example in the data.table fread vignette:

library(data.table)
DT = fread(text = "colA,colB,colCn1,apple,TRUEn2,banana,FALSEn3,orange,TRUE")
DT
sapply(DT, class)

The result is a data.table with three rows and three columns, and the column classes are integer, character and logical. Nothing in the call told fread the separator, that the first line is a header, or what type each column holds: it detected all three. Compare it with a forced type:

DT2 = fread(text = "id,scoren007,4n012,9", colClasses = c(id = "character"))
DT3 = fread(text = "id,scoren007,4n012,9", keepLeadingZeros = TRUE)

Here the id values 007 and 012 stay as text in both calls. Without either argument, a numeric-looking column is read as a number and the leading zeros are lost. The keepLeadingZeros argument, which is FALSE by default, reads numeric-looking columns with leading zeros as character; the documentation notes this can make header detection guess TRUE, so check the header after using it.

How to read the output

By default fread returns a data.table, which is also a data.frame, so base R functions and packages that accept data frames still work on it. If you need a plain data.frame, pass data.table=FALSE; the default can also be changed with the option datatable.fread.datatable. For readers moving from base R, the guides to data frames in R and the dplyr package cover what to do with the table after loading.

Check four things after every read:

  • Dimensions and column names. Confirm the row count against the source system. If check.names is left at its default of FALSE, names are kept as they appear in the header rather than made syntactically valid.
  • Column classes. Type guessing works from a sample of 10,000 rows: 100 contiguous rows at 100 equally spaced points, including the beginning, middle and end of the file. The type order is logical, integer, integer64, double, character. If a later value does not fit the guessed type, fread rereads those columns automatically from the beginning, so a late text value does not silently corrupt a numeric column.
  • Large integers. A column of integers above 231 is returned as integer64. Use integer64="character" or "double" if downstream code cannot handle that class.
  • Dates and times. Unmarked date-time values are read as UTC POSIXct, because tz defaults to “UTC”. With tz="" they are read as character, so you can parse them with the time zone your study actually used. fwrite() writes UTC with a trailing Z, which fread reads back consistently, so a write-then-read round trip does not shift times.

The key and index arguments pass directly to setkey and setindexv, but only when data.table=TRUE, so you can sort and index on load for later joins.

Troubleshooting fread

Empty fields are read as NA, or not

With the default na.strings, an empty field written as two commas (,,) is read as NA in every column type, character columns included, while an empty quoted string (,””,) is read as an empty string. Set na.strings="NA" to read the literal text NA as missing and not the empty field, or na.strings=NULL to read ,, as an empty string. Decide this once, from the data dictionary of your source, rather than letting the default decide.

Reading stops early with a warning

fread reads to the first blank line and, if text follows it (a footer, a notes block, a second table), stops with a warning. The behaviour is controlled by blank.lines.skip, which is FALSE by default; single-column input is the exception. Look at the end of the file in a text editor, then either set blank.lines.skip=TRUE or limit the read with nrows.

Header notes above the table

The default skip="__auto__" finds the first row with a consistent column count, which skips irregular header information. To be explicit, give a number (skip the first n rows) or a string: skip="participant_id" starts reading at the line containing that text.

Rows with different numbers of fields

fread is documented for files where every row has the same column count. If rows are ragged, fill=TRUE estimates the number of columns and fills short rows; an integer value gives an upper bound.

Wrong separator or decimal mark

Separator detection runs before type detection, and the file extension plays no role. A .txt file is read the same way as a .csv. To override, set sep explicitly; sep=NULL or sep="" reads each line into one character column, as readLines() does. The dec argument defaults to “auto”, trying “.” and then “,”.

Quotes, line endings and encoding

Line endings (n, rn, r and nr) are detected automatically. A field with unbalanced quotes is retried as unquoted, and quote="" reads the file as it stands. The encoding argument (“unknown”, “UTF-8” or “Latin-1”) only marks strings; it does not re-encode them, so a file in another encoding needs converting before it is read.

Compressed and archived files

.gz and .bz2 files are decompressed by extension when R.utils is installed. A .zip or .tar archive holding a single file can be read; an archive with several files produces an error, so extract it first.

Warnings from colClasses

When a forced type cannot be applied safely, fread keeps the column as detected and warns. In list form, the column numbers in colClasses refer to the columns in the file, not to the columns left after select or drop.

Free alternatives to fread

The functions named in the fread documentation as its counterparts are read.csv() and read.delim() from base R, which come with R itself. The guides to read.table in R and reading CSV files into R cover them in detail, and importing data in R places them next to the other import routes. The comparison below is limited to what the fread documentation itself states.

Behaviour fread (data.table) read.csv() and read.delim() (base R)
Separator, header and column types Detected automatically Set through arguments such as sep and colClasses
Positioning in the documentation Described as similar to read.csv() and read.delim() but faster and more convenient The functions fread is compared with
Return type data.table by default; data.frame with data.table=FALSE data.frame
Missing-value default ,, read as NA in every column type (na.strings) Set through na.strings

Choose by what your script needs. For small files in a project that avoids extra dependencies, base R is sufficient. When the files are large, irregular in their types, or you want detection of separators and dates without extra arguments, fread is the documented convenience option. This page does not quote speed measurements, because the sources used here give none; time both on your own file if speed is the deciding factor.

Sources

Data: fread arguments that matter for research data: defaults and effects

Compares eleven fread() arguments from the data.table reference documentation: the default value, what each argument does and the research-data problem it addresses. Compiled from the fread reference page and the Fast Read and Fast Write vignette; defaults are those listed in the Usage section of the development documentation.

fread arguments that matter for research data: defaults and effects
ArgumentDefaultDocumented behaviourResearch-data use
integer64"integer64"Reads integers above 2^31 as bit64::integer64; alternatives are double/numeric or characterLong participant, sample or registry identifiers
keepLeadingZerosFALSETRUE reads numeric-looking columns with leading zeros as characterIdentifiers such as 007 that must keep their zeros
colClassesNULLSets column types by an unnamed or named vector or list; a failed conversion is aborted for that column with a warningForcing identifiers to character
select / dropNULLKeep or drop columns by name or number; select can carry types and sets result orderLimiting memory on wide exports
nrowsInfnrows=0 returns column names and typed empty columns, a dry run of a large fileInspecting a large file before reading it
na.stringsgetOption("datatable.na.strings", "NA"),, is read as NA in all column types; ,"", is an empty stringMatching the data dictionary's missing-value rule
skip"__auto__"Starts at the first row with a consistent column count; a number or a string overrides itFiles with notes above the table
fillFALSETRUE estimates the column count and fills short rows; an integer sets an upper boundRagged exports
blank.lines.skipFALSEReading stops with a warning at a blank line followed by text unless the input has one columnFiles with a footer or a second table
tz"UTC"Unmarked date-times are read as UTC POSIXct; tz="" reads them as characterStudy-specific time zones
data.tableTRUEFALSE returns a data.framePassing the result to code that expects a data.frame

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about fread in R: Syntax, Arguments and Examples

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →