# Tibbles {#sec-tibbles}

```{r}
#| results: "asis"
#| echo: false
source("_common.R")
status("complete")
```

## Introduction

Throughout this book we work with "tibbles" instead of R's traditional `data.frame`.
Tibbles *are* data frames, but they tweak some older behaviors to make your life a little easier.
R is an old language, and some things that were useful 10 or 20 years ago now get in your way.
It's difficult to change base R without breaking existing code, so most innovation occurs in packages.
Here we will describe the **tibble** package, which provides opinionated data frames that make working in the tidyverse a little easier.
In most places, we use the term tibble and data frame interchangeably; when we want to draw particular attention to R's built-in data frame, we'll call them `data.frame`s.

### Prerequisites

In this chapter we'll explore the **tibble** package, part of the core tidyverse.

```{r}
#| label: setup
#| message: false

library(tidyverse)
```

## Tibbles vs. data.frame

There are two main differences in the usage of a tibble vs. a classic `data.frame`: printing and subsetting.
If these difference cause problems when working with older packages, you can turn a tibble back to a regular data frame with `as.data.frame()`.

### Printing

Tibbles have a refined print method that shows only the first 10 rows, and all the columns that fit on screen.
This makes it much easier to work with large data.
In addition to its name, each column reports its type, a nice feature inspired by `str()`:

```{r}
tibble(
  a = lubridate::now() + runif(1e3) * 86400,
  b = lubridate::today() + runif(1e3) * 30,
  c = 1:1e3,
  d = runif(1e3),
  e = sample(letters, 1e3, replace = TRUE)
)
```

Where possible, tibbles also use color to draw your eye to important differences.
One of the most important distinctions is between the string `"NA"` and the missing value, `NA`:

```{r}
tibble(x = c("NA", NA))
```

Tibbles are designed to avoid overwhelming your console when you print large data frames.
But sometimes you need more output than the default display.
There are a few options that can help.

First, you can explicitly `print()` the data frame and control the number of rows (`n`) and the `width` of the display.
`width = Inf` will display all columns:

```{r}
library(nycflights13)

flights |> 
  print(n = 10, width = Inf)
```

You can also control the default print behavior by setting options:

-   `options(tibble.print_max = n, tibble.print_min = m)`: if more than `n` rows, print only `m` rows.
    Use `options(tibble.print_min = Inf)` to always show all rows.

-   Use `options(tibble.width = Inf)` to always print all columns, regardless of the width of the screen.

You can see a complete list of options by looking at the package help with `package?tibble`.

A final option is to use RStudio's built-in data viewer to get a scrollable view of the complete dataset.
This is also often useful at the end of a long chain of manipulations.

```{r}
#| eval: false

flights |> View()
```

### Extracting variables

So far all the tools you've learned have worked with complete data frames.
If you want to pull out a single variable, you can use `dplyr::pull()`:

```{r}
tb <- tibble(
  id = LETTERS[1:5],
  x1  = 1:5,
  y1  = 6:10
)

tb |> pull(x1) # by name
tb |> pull(1)  # by position
```

`pull()` also takes an optional `name` argument that specifies the column to be used as names for a named vector, which you'll learn about in @sec-vectors.

```{r}
tb |> pull(x1, name = id)
```

You can also use the base R tools `$` and `[[`.
`[[` can extract by name or position; `$` only extracts by name but is a little less typing.

```{r}
# Extract by name
tb$x1
tb[["x1"]]

# Extract by position
tb[[1]]
```

Compared to a `data.frame`, tibbles are more strict: they never do partial matching, and they will generate a warning if the column you are trying to access does not exist.

```{r}
# Tibbles complain a lot:
tb$x
tb$z

# Data frame use partial matching and don't complain if a column doesn't exist
df <- as.data.frame(tb)
df$x
df$z
```

For this reason we sometimes joke that tibbles are lazy and surly: they do less and complain more.

### Subsetting

Lastly, there are some important differences when using `[`.
With `data.frame`s, `[` sometimes returns a `data.frame`, and sometimes returns a vector, which is a common source of bugs.
With tibbles, `[` always returns another tibble.
This can sometimes cause problems when working with older code.
If you hit one of those functions, just use `as.data.frame()` to turn your tibble back to a `data.frame`.

### Exercises

1.  How can you tell if an object is a tibble?
    (Hint: try printing `mtcars`, which is a regular `data.frame`).

2.  Compare and contrast the following operations on a `data.frame` and equivalent tibble.
    What is different?
    Why might the default `data.frame` behaviors cause you frustration?

    ```{r}
    #| eval: false

    df <- data.frame(abc = 1, xyz = "a")
    df$x
    df[, "xyz"]
    df[, c("abc", "xyz")]
    ```

3.  If you have the name of a variable stored in an object, e.g. `var <- "mpg"`, how can you extract the reference variable from a tibble?

4.  What does `tibble::enframe()` do?
    When might you use it?

5.  What option controls how many additional column names are printed at the footer of a tibble?

## Summary

If this chapter leaves you wanting to learn more about tibbles, you might enjoy `vignette("tibble")`.
