Skip to content

Instantly share code, notes, and snippets.

@multidis
Created December 16, 2013 22:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save multidis/7995512 to your computer and use it in GitHub Desktop.
Save multidis/7995512 to your computer and use it in GitHub Desktop.
Passing lists as function arguments in R. Frequently helps reduce code repetition (e.g. if/else calls of different functions with mostly the same arguments). NOTE: always consider a closure function as FP alternative to this method of dealing with repetitive code elements.
## regular case
foo <- function(a, b, c) a + b - c ## does something
foo2 <- function(b, c) b + c ## also some function
foo(a=1, b=2, c=5)
foo2(b=2, c=5) ## repeating list of multiple arguments
## passing a list
arg.list <- list(b=2, c=5)
do.call(foo, c(list(a=1), arg.list))
do.call(foo2, arg.list)
## writing a closure function sometimes may be better!
## example of reasonable use of list passing
## from https://gist.github.com/multidis/7995062
arg.list <- list(X=vsets.list, FUN=varsubs.miscclass.eval, Xtra=Xtra, Yfac=Yfac,
Xtst=Xtst, Ytst=Ytst, methods.caret=methods.list)
if (ncores>1) {
vsets.compar <- do.call(mclapply, c(arg.list,list(mc.cores=ncores)))
} else {
vsets.compar <- do.call(lapply, arg.list)
}
@ksawicka
Copy link

Very helpful! Thank you.

@sebastiansauer
Copy link

Hi there, great stuff! Are you aware of a purrr/tidyverse version of lists with fun args?

@multidis
Copy link
Author

Thanks for the pointer - purrr looks fairly helpful.

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