Created
December 16, 2013 22:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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) | |
} |
Hi there, great stuff! Are you aware of a purrr/tidyverse version of lists with fun args?
Thanks for the pointer - purrr looks fairly helpful.
Wonderful! Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very helpful! Thank you.