% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/faq-developer.R
\name{theory-faq-recycling}
\alias{theory-faq-recycling}
\alias{vector_recycling_rules}
\title{FAQ - How does recycling work in vctrs and the tidyverse?}
\description{
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:
\itemize{
\item Vectors of size 1 will be recycled to the size of any other vector
\item Otherwise, all vectors must have the same size
}
}
\section{Examples}{
Vectors of size 1 are recycled to the size of any other vector:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{tibble(x = 1:3, y = 1L)
#> # A tibble: 3 x 2
#>       x     y
#>   <int> <int>
#> 1     1     1
#> 2     2     1
#> 3     3     1
}\if{html}{\out{</div>}}

This includes vectors of size 0:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{tibble(x = integer(), y = 1L)
#> # A tibble: 0 x 2
#> # i 2 variables: x <int>, y <int>
}\if{html}{\out{</div>}}

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{tibble(x = 1:3, y = 4:7)
#> Error in `tibble()`:
#> ! Tibble columns must have compatible sizes.
#> * Size 3: Existing data.
#> * Size 4: Column `y`.
#> i Only values of size one are recycled.
}\if{html}{\out{</div>}}
}

\section{vctrs backend}{
Packages in r-lib and the tidyverse generally use
\code{\link[=vec_size_common]{vec_size_common()}} and
\code{\link[=vec_recycle_common]{vec_recycle_common()}} as the backends for
handling recycling rules.
\itemize{
\item \code{vec_size_common()} returns the common size of multiple vectors, after
applying the recycling rules
\item \code{vec_recycle_common()} goes one step further, and actually recycles
the vectors to their common size
}

\if{html}{\out{<div class="sourceCode r">}}\preformatted{vec_size_common(1:3, "x")
#> [1] 3

vec_recycle_common(1:3, "x")
#> [[1]]
#> [1] 1 2 3
#> 
#> [[2]]
#> [1] "x" "x" "x"

vec_size_common(1:3, c("x", "y"))
#> Error:
#> ! Can't recycle `..1` (size 3) to match `..2` (size 2).
}\if{html}{\out{</div>}}
}

\section{Base R recycling rules}{
The recycling rules described here are stricter than the ones generally
used by base R, which are:
\itemize{
\item If any vector is length 0, the output will be length 0
\item Otherwise, the output will be length \code{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 \code{vignette("type-size")}.
}

