Skip to content

Instantly share code, notes, and snippets.

@mja
Created November 16, 2010 15:47
Show Gist options
  • Save mja/701955 to your computer and use it in GitHub Desktop.
Save mja/701955 to your computer and use it in GitHub Desktop.
Using the ... arguments programmatically with do.call
do.call('+', list(1, 2))
f <- function(...) {
arguments <- list(...) # turn them into a list
for(arg in arguments ) { # loop through them
# process each argument
}
}
# Use the ... to make a function that can process an arbitrary number of objects
f1 <- function(...) {
arguments <- list(...) # turn them into a list
collection <- new.env() # store up calculations on each argument
counter <- # arbitrary names
for(arg in arguments ) { # loop through them
# do some processing here
results <- some.function.of(arg)
# save the result
assign(as.character(counter), result, envir=collection)
counter <- counter + 1
}
# now here is the magic...
# f2 is also a function with the form `function(...) {}`
# ________/
# /
do.call(f2, as.list(collection))
# \________/
# \
# \________________________----
# / | \
# which is like we wrote `f2(result0, result1, result2, ...)`
}
> paste
function (..., sep = " ", collapse = NULL)
.Internal(paste(list(...), sep, collapse))
<environment: namespace:base>
@isomorphisms
Copy link

Thanks @mja!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment