2 Vectors, lists, and tibbles

It’s helpful to know a little bit about how data structures are organised in R. In this chapter, you’ll learn about vectors, lists, and tibbles.

2.1 Atomic vectors

The atomic vectors are the “atoms” of R, the simple building blocks upon which all else is built. There are four types of atomic vector that are important for data analysis:

  • integer vectors <int> contain integers.
  • double vectors <dbl> contain real numbers.
  • character vector <chr> contain strings made with "".
  • logical vectors <lgl> contain TRUE or FALSE.

Integer atomic vectors only contain integers, double atomic vectors only contain doubles, and so on.

All vectors can also contain the missing value NA. You’ll learn more about missing values later on. Collectively integer and double vectors are known as numeric vectors. The difference is rarely important in R.

You create atomic vectors by hand with the c() function:

2.1.1 Subsetting

Use [[ extract a single value out of a vector:

Use [ to extract multiple values:

The names of these functions are [ and [[ but are used like x[y] (pronounced “x square-bracket y”) and x[[y]] (pronounced “x double-square-bracket y”). You can get help on them with ?`[` and ?`[[`.

2.1.2 Augmented vectors

Augmented vectors are atomic vectors with additional metadata. There are four important augmented vectors:

  • factors <fct>, which are used to represent categorical variables can take one of a fixed and known set of possible values (called the levels).

  • ordered factors <ord>, which are like factors but where the levels have an intrinsic ordering (i.e. it’s reasonable to say that one level is “less than” or “greater than” another variable).

  • dates <dt>, record a date.

  • date-times <dttm>, which are also known as POSIXct, record a date and a time.

For now, you just need to recognize these when you encounter them. You’ll learn how to create each type of augmented vector later in the course.

2.2 Lists

Unlike atomic vectors, which can only contain a single type, lists can contain any collection of R objects. The following reading will introduce you to lists.

2.3 Tibbles

You can think of tibbles as lists of vectors, where every vector has the same length. There are two ways to create tibbles by hand:

  1. From individual vectors, each representing a column:

  2. From individual values, organised in rows:

Typically it will be obvious whether you need to use tibble() or tribble(). One representation will either be much shorter or much clearer than the other.