# [R] Splitting vector into individual elements

Gabor Grothendieck ggrothendieck at myway.com
Thu Sep 16 03:16:51 CEST 2004

```Gabor Grothendieck <ggrothendieck <at> myway.com> writes:

:
: Paul Roebuck <roebuck <at> odin.mdacc.tmc.edu> writes:
:
: :
: : On Wed, 15 Sep 2004, Peter Dalgaard wrote:
: :
: : > Paul Roebuck <roebuck <at> odin.mdacc.tmc.edu> writes:
: : >
: : > > Is there a means to split a vector into its individual
: : > > elements without going the brute-force route for arguments
: : > > to a predefined function call?
: : > >
: : > >     offred.rgb <- c(1, 0, 0) * 0.60;
: : > >
: : > >     ## Brute force style
: : > >     offred.col <- rgb(offred.rgb[1],
: : > >                       offred.rgb[2],
: : > >                       offred.rgb[3],
: : > >                       names = "offred")
: : > >     ## Desired style
: : > >     offred.col <- rgb(silver.bullet(offred.rgb),
: : > >                       names = "offred")
: : >
: : > The closest is probably this:
: : >
: : > offred.col <- do.call("rgb", c(as.list(offred.rgb),
: : >                                list(names="offred")))
: : >
: :
: : Everyone offered 'do.call' as the solution. While that
: : works, is it to say that there is no means of expanding
: : the expression as an argument to the original function?
:
: This is not a true answer to the question of expanding a list
: into arguments without using do.call but it does allow you to
: carry out either syntax in this particular case using S3
: dispatch:
:
: R> silver.bullet <- as.list
: R> rgb <- function(x, ...) UseMethod("rgb")
: R> rgb.list <- function(x, ...) rgb(x[[1]],x[[2]],x[[3]],...)
: R> rgb.default <- graphics::rgb
:
: R> offred.rgb <- c(1, 0, 0) * 0.60;
: R> # original syntax
: R> rgb(offred.rgb[1], offred.rgb[2], offred.rgb[3], names = "offred")
:    offred
: "#990000"
: R> # list syntax
: R> rgb(silver.bullet(offred.rgb), names = "offred")
:    offred
: "#990000"

Here is a second, different approach.

Again, it is not exactly what you are asking for since silver.bullet,
here called flatten.args, is applied to the function rather than the
argument in question and operates on all arguments, not just one but
I think its closer in spirit to your query than my previous solution:

flatten.args <- function(f)
function(...) {
L <- list()
for(i in list(...)) L <- c(L, unlist(i))
do.call(as.character(substitute(f)), L)
}

flatten.args(rgb)(0.6 * c(1,0,0), name = "offred")

```