Brian Diggs - 1 year ago 70

R Question

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 arerecycledas 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

}

where

`a`

`b`

`c`

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)
}
```