Skip to content

Instantly share code, notes, and snippets.

@bjcairns
Last active January 17, 2020 13:57
Show Gist options
  • Save bjcairns/99b6073f257b295d1351c225cbeed917 to your computer and use it in GitHub Desktop.
Save bjcairns/99b6073f257b295d1351c225cbeed917 to your computer and use it in GitHub Desktop.
Handling argument priorities (specified vs argument list vs default) in R
# Sometimes during repeat calls to a function, it may be helpful if arguments used in a
# previous call are passed as a list to the function in subsequent calls, to be
# superseded if individual arguments of the same name are given.
#
# The following function prioritises specified arguments (including ... arguments) over an
# argument list, and the argument list over default values.
handle_args <- function(arg1 = 1, arg2 = 2, arglist = list(), ...) {
# Copy default arguments
dargs <- as.list(sys.frame(sys.nframe()))
dargs <- lapply(dargs, eval, parent.frame())
# Copy specified arguments
cargs <- as.list(match.call())[-1L]
cargs <- lapply(cargs, eval, parent.frame())
# Remove arglist from the default and specified arguments
dargs[["arglist"]] <- NULL
cargs[["arglist"]] <- NULL
# Compile arguments into a single list:
# - privilege the arglist elements over the defaults
all_args <- append(arglist, dargs[!(names(dargs) %in% names(arglist))])
# - privilege specified arguments over the rest
all_args <- append(cargs, all_args[!(names(all_args) %in% names(cargs))])
return(all_args)
}
## Examples
#
# handle_args(arglist = list(arg1 = 3))
# handle_args(arglist = list(arg1 = 3, arg3 = 0))
# handle_args(arg1 = 4, arglist = list(arg1 = 3, arg3 = 0))
# handle_args(arg1 = 4, arglist = list(arg1 = 3, arg3 = 0), arg3 = 1)
# handle_args(arg1 = 4, arglist = list(arg1 = 3, arg2 = 4, arg3 = 0), arg3 = 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment