
```{r, child = "../setup.Rmd", include = FALSE}
```

Recycling describes the concept of repeating elements of one vector to match the size of another. There are two rules that underlie the "tidyverse" recycling rules:

- Vectors of size 1 will be recycled to the size of any other vector

- Otherwise, all vectors must have the same size

# Examples

```{r, warning = FALSE, message = FALSE, include = FALSE}
library(tibble)
```

Vectors of size 1 are recycled to the size of any other vector:

```{r}
tibble(x = 1:3, y = 1L)
```

This includes vectors of size 0:

```{r}
tibble(x = integer(), y = 1L)
```

If vectors aren't size 1, they must all be the same size. Otherwise, an error is thrown:

```{r, error = TRUE}
tibble(x = 1:3, y = 4:7)
```

# vctrs backend

Packages in r-lib and the tidyverse generally use [vec_size_common()] and [vec_recycle_common()] as the backends for handling recycling rules.

- `vec_size_common()` returns the common size of multiple vectors, after applying the recycling rules

- `vec_recycle_common()` goes one step further, and actually recycles the vectors to their common size

```{r, error = TRUE}
vec_size_common(1:3, "x")

vec_recycle_common(1:3, "x")

vec_size_common(1:3, c("x", "y"))
```

# Base R recycling rules

The recycling rules described here are stricter than the ones generally used by base R, which are:

- If any vector is length 0, the output will be length 0

- Otherwise, the output will be length `max(length_x, length_y)`, and a warning will be thrown if the length of the longer vector is not an integer multiple of the length of the shorter vector.

We explore the base R rules in detail in `vignette("type-size")`.
