% Generated by roxygen2: do not edit by hand % Please edit documentation in R/recycle.R \name{vector_recycling_rules} \alias{vector_recycling_rules} \title{Recycling rules used by r-lib 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{
}}\preformatted{tibble(x = 1:3, y = 1L) #> # A tibble: 3 x 2 #> x y #> #> 1 1 1 #> 2 2 1 #> 3 3 1 }\if{html}{\out{
}} This includes vectors of size 0: \if{html}{\out{
}}\preformatted{tibble(x = integer(), y = 1L) #> # A tibble: 0 x 2 #> # ... with 2 variables: x , y }\if{html}{\out{
}} If vectors aren't size 1, they must all be the same size. Otherwise, an error is thrown: \if{html}{\out{
}}\preformatted{tibble(x = 1:3, y = 4:7) #> Error: #> ! 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{
}} } \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{
}}\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{
}} } \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")}. } \keyword{internal}