Brian Diggs Brian Diggs - 1 year ago 61
R Question

Implementation of standard recycling rules

One nice feature of R which is related to its inherent vectorized nature is the recycling rule described in An Introduction to R in Section 2.2.

Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated.

Most standard functions use this, but the code that does so is buried in the underlying C code.

Is there a canonical way to implement the standard recycling rules for a function entirely in R code? That is, given a function like

mock <- function(a, b, c) {
# turn a, b, and c into appropriate recycled versions

# do something with recycled a, b, and c in some appropriately vectorized way

, and
are vectors, possibly of different lengths and unknown types/classes, is there a canonical way to get a new set of vectors which are recycled according to the standard recycling rules? In particular, I can't assume that "do something" step will do the proper recycling itself, so I need to do it myself beforehand.

Answer Source

I've used this in the past,

expand_args <- function(...){
  dots <- list(...)
  max_length <- max(sapply(dots, length))
  lapply(dots, rep, length.out = max_length)