6.2 Essential readr commands

The process of reading some data structure is known as parsing. We usually parse entire files of data. However, as data files typically consist of columns of variables, we also need to consider how individual vectors are parsed.29

6.2.1 Parsing vectors

The parse_ functions provided by readr take a character vector as their main input argument and return a more specialised vector (e.g., logical, integer, or date values) as output vector. Some examples of the corresponding parse_ commands are:

A uniform na argument allows specifying which string should be treated as missing data in all parse_ functions:

If the process of parsing fails for an element, a warning is issued and the problematic element is missing (NA) in the output vector:

We can use problems() on the parsed vector to see which problems occurred during parsing:

The range of important parsers matches the range of data types that we typically deal with. Important parsers include the following:

  1. parse_logical() parses logical values (TRUE vs. FALSE);

  2. parse_integer() parses integer numbers (1, 2, 3, etc.);

  3. parse_double() is a strict numeric parser, which enforces numeric output:

When using a decimal mark different from “.” (used in the U.S.) we need to specify this by providing the locale argument:

  1. parse_number() is a more flexible numeric parser, which ignores prefixes and postfixes, but only reads the first number of a character string:

In addition, parse_number allows specifying both a decimal_mark and grouping_mark in its locale argument for reading country-specific number formats:

  1. parse_character() seems trivial, but allows dealing with different character encodings:

The issue of character encodings is — like spelling, typography, and punctuation — a topic that is incredibly important, yet most people seem almost aggressively allergic to it. Fortunately, there are solid standards for defining characters and encodings. If you never want to hear about them again, just remember that Unicode and UTF-8 are our friends (and see the Wikipedia articles on Unicode, UTF-8, and especially the List of Unicode characters for details, and read this article at Kunststube.net for further information).

We will re-visit the issue of character encodings in Chapter 9 on Text data (see Section 9.2.2).

  1. parse_factor() creates factors, a data structure often used to represent categorical variables with fixed and known values (e.g., the different conditions of an experiment, or the treatment levels in a study):
  1. parse_date(), parse_datetime() and parse_time() allow parsing various date and time specifications:

Reading dates and times often requires specifying the details of the current date-time format (see the documentation to ?parse_datetime for details).

In R, dates are typically represented by a 4-digit year (%Y), a 2-digit month (%m), and a 2-digit day (%d), all separated by either “-” or “/”:

Note the ambiguity of a date string like "2018-12-10" (in which month and day could be confused) or even "08/10/12" (in which even the year is unclear):

See Chapter 10 on Time data for additional details on handling dates and times in R.

6.2.2 Parsing files

The ease or difficulty of loading a data file depends on the sensibility of whoever saved it. If the originator of the file used a file format that is universal and easily exchanged (e.g., a csv file in a common encoding format), reading the data into R — or any other data analysis software — is easy and straightforward. Unfortunately, many people still insist on saving and exchanging specialized or proprietary file formats (e.g., xls or sav files). In the following, we outline some basic methods of reading different kinds of files that should cover 95% of all cases, and provide some pointers to resources that allow dealing with the remaining 5%.


A common and sensible file format for data separates variables (columns) by commas, which is why it is called a comma separated value (or csv) file. The best way to read such files within the tidyverse is by using the readr function read_csv. We have used this command in this book before (e.g., to read in http://rpository.com/ds4psy/data/data_t1.csv above). Depending on the location of the data file and our preferred way of expressing the path to it, here are 5 possible ways of reading this file:

Actually, base R (or rather the R default package utils) also provides a function read.csv() to achieve the same thing:

However, note that the objects resulting from our calls of read_csv and read.csv (i.e., dt and df, respectively) are similar, but not identical:

Unless we really need a data frame, working with tibbles — and the read_csv() command from readr — is typically safer than using read.csv(), as it reduces the likelihood of strange things happening when reading in data files.

Variants (read_csv2 and read_tsv)

In many countries (e.g., European countries like Germany), commas (,) are used as the decimal mark (e.g., “pi is close to 3,1416.”) and hence are not a good separator for variables (columns). In these locations, variables are typically separated by semi-colons (;). For such files, both readr and base R provide variants of the above commands that follow this convention. For instance, to read in the file http://rpository.com/ds4psy/data/data_t1_de.csv we can use:

Sometimes, the variables (columns) of a data file are separated by tabs (\t), which prompts the use of read_tsv. To read in the tab-separated data file http://rpository.com/ds4psy/data/data_t1_tab.csv we use:


All the read_ commands encountered so far are special instances of the more general read_delim() function, which reads delimited files into a tibble and allows specifying various additional arguments.

Suppose we want to read a file like http://rpository.com/ds4psy/data/data_1.dat, which is known to include 4 variables:

  • the initials of participants;
  • their age;
  • their telephone number;
  • their pwd to some account.

Inspecting the file shows the following:

  1. The data is delimited, but by a full stop (aka. point or period, i.e., .) rather than by a comma or semi-colon. As a consequence, we need to use read_delim and explicitly specify the delimiting symbol as ".".

  2. As the file does not include variable names (in the first row), we provide them with the col_names argument (which accepts a vector of characters).

  3. Some lines are shorter than most others. Close inspection reveals that they include either -99 or -77. As these symbols are frequently used to express missing values, we supply them to the na argument (again as a vector of characters).


When data is not delimited by some special character, we could describe data by knowing the positions of variables and values in a file. If this is the case, we can use the command read_fwf (with “fwf” standing for fixed-width files) and specify the positions of the variables and values (provided that they are the same for all rows). For instance, the file at http://rpository.com/ds4psy/data/data_2.dat contains the same variables as the previous file (data_1), but does not include missing values and can therefore be read in the following way:

6.2.3 Writing files

To write a data file to a local directory, use one of the following readr functions (from more general to more specific):

Alternatively, base R (or the utils package) provides the following options (and note that the path argument from above is named file here):

R also provides save and load functions for storing an external representation of R objects to an (.RData) file. Although this is a convenient way of saving some current state within R, such files can only be opened from an R environment. Hence, to make your future life (and the lives of your colleagues) easier, we recommend sticking to write_csv (i.e., csv files), unless there are good reasons for using another file format.

6.2.4 Other data formats and programs

Sometimes we have to import files stored in the proprietary format of other software packages. Fortunately, there exist dedicated packages for most cases.

For rectangular data

  • The readxl package allows reading data from MS Excel files (both .xls and .xlsx).

  • The haven package allows reading data from SPSS, Stata, and SAS files.

  • The DBI package provides an interface to optain R data frames from relational databases, but requires the specific database backend (e.g., RMySQL, RSQLite, RPostgreSQL).

For hierarchical data

  • Use jsonlite for json, and xml2 for XML files.

For web log data

  • The readr command read_log imports Apache style log files. (For additional functionality, check out the webreadr package, which builds upon read_log.)

For additional information on importing other types of data, see the official guide on R Data Import/Export.

6.2.5 Conclusion

The more experience you accumulate with reading and sharing data, the more relevant the following insight becomes: Avoid using exotic or proprietary file formats — in R, but also in other software programs. Saving some data as a Rdata, sav, or xls file makes you (and anyone else who may ever be using your data) dependent on particular software products. If saving something in plain text format (e.g., a csv file with UTF-8 encoding) is an option, it is much more flexible and an easy way of reducing future frustration.

  1. We only cover the most common parse commands here (see Section 11.3 Parsing a vector of r4ds (Wickham & Grolemund, 2017) for details).